arrays - 使用 "+="运算符连接到可选数组

标签 arrays swift option-type xcode6-beta6

我正在尝试将多个字符串附加到一个数组。 此代码按预期工作:

var myArray: [String] = []
myArray += ["dog", "cat"]

这给了我一个错误:

var myArray: [String]! = []
myArray += ["dog", "cat"] //error: '[String]!' is not identical to 'UInt8'

这是一个错误,还是连接到一个不应该工作的可选数组?

最佳答案

myArray 是可选的,因此您必须显式地解包它才能使追加工作:

myArray! += ["dog", "cat"]

这听起来违反直觉,因为隐式解包可选的目的是避免手动解包。但是文档说:

An implicitly unwrapped optional is a normal optional behind the scenes, but can also be used like a nonoptional value, without the need to unwrap the optional value each time it is accessed

我的解释是,作为引擎盖下的可选枚举,+= 运算符应用于枚举,而不是可选本身包装的实际类型。

关于arrays - 使用 "+="运算符连接到可选数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25460415/

相关文章:

java - 无法访问 while 循环内初始化的数组

c - C 中的 print 语句出错

ios - UIViewPropertyAnimator 不会停止在 stopAnimation 上

ios - 设置导航栏颜色

ios - 如何使用 Optionals 来阻止 Swift 中的编译器错误

ios - 为什么我得到一个 "Value of optional type UIFont not unwrapped",但解包给出 "unexpectedly found nil while unwrapping an optional"?

c - 嵌套 for 循环数组随机数

C:填充多维数组

swift - 如何仅在 Swift 中将一个 View Controller 的方向锁定为纵向模式

rust - 在 Rust 中处理多个 `Option<T>` 的惯用方法是什么?