xcode - “+=”不能应用于两个 [AnyObject] 操作数

标签 xcode swift autolayout

我有以下代码来尝试创建一个约束数组以添加到 View 中:

let views = ["button": button]
let metrics = ["margin": 16]

var constraints: [AnyObject] = []
constraints += NSLayoutConstraint.constraintsWithVisualFormat("|-margin-[button]-margin-|", options: 0, metrics: metrics, views: views)

根据我对 Swift 数组的理解,我应该能够将它们“+=”在一起以连接两者,但我收到一个错误:

"Binary operator '+=' cannot be applied to two [AnyObject] operands"

这段代码有什么问题?

最佳答案

这不是因为运营商。 这是因为您传递的是 Int,实际上应该传递 NSLayoutFormatOptions 枚举类型。

如果您为 options 参数传入 NSLayoutFormatOptions 枚举之一,错误将会消失:

constraints += NSLayoutConstraint.constraintsWithVisualFormat("|-margin-[button]-margin-|", options: .AlignAllLeft, metrics: metrics, views: views)

或者您也可以使用您想要使用的 Int 值初始化 NSLayoutFormatOptions,如下所示:

NSLayoutFormatOptions(rawValue: 0)

0 在 Objective-C 中可以工作,但你需要在 Swift 中使用实际的枚举值。 在许多情况下,Swift 错误仍然经常具有误导性,就像这个例子。

希望这有帮助。

关于xcode - “+=”不能应用于两个 [AnyObject] 操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30762779/

相关文章:

ios - 我的应用程序在编译时立即崩溃

c - 在 Swift Framework 中导入的 C 函数中设置文件路径

Xcode、Swift、无法识别的单元测试类/方法

iOS >> 自动布局 >> iPhone 4 与 iPhone 5 >> 设置多个对象来改变大小

ios - 自动布局的困难

ios - 将等宽 View 添加到 Superview - Autolayout iOS

ios - 在 UITableView 搜索点击上显示新 Controller

swift - 升级到 Swift 3.0 后未收到来自 Azure 的 APNS 消息

swift - UITableView 不显示原型(prototype)单元格

ios - 使用 TableView 或 CollectionView 时的 Swift、Slim Controller 代码