Swift beta 5 已添加此功能,并且您在几次尝试中就掌握了新方法。展开运算符! 和? 现在将值传递给运算符或方法调用。也就是说,您可以通过以下任何方式添加到该数组中:
dict["key"]! += [4]
dict["key"]!.append(4)
dict["key"]?.append(4)
与往常一样,请注意您使用的运算符 - 强制解包不在字典中的值会导致运行时错误:
dict["no-key"]! += [5] // CRASH!
而使用可选链会默默地失败:
dict["no-key"]?.append(5) // Did it work? Swift won't tell you...
理想情况下,您可以使用新的空合并运算符 ?? 来解决第二种情况,但现在这不起作用。
Swift beta 5 之前的答案:
这是 Swift 的一个怪癖,它不可能做你想做的事。问题是任何 Optional 变量的 value 实际上是一个常量——即使在强制展开时也是如此。如果我们只定义一个 Optional 数组,以下是我们能做和不能做的事情:
var arr: Array<Int>? = [1, 2, 3]
arr[0] = 5
// doesn't work: you can't subscript an optional variable
arr![0] = 5
// doesn't work: constant arrays don't allow changing contents
arr += 4
// doesn't work: you can't append to an optional variable
arr! += 4
arr!.append(4)
// these don't work: constant arrays can't have their length changed
您在使用字典时遇到问题的原因是下标字典会返回一个可选值,因为无法保证字典将具有该键。因此,字典中的数组与上面的可选数组具有相同的行为:
var dict = Dictionary<String, Array<Int>>()
dict["key"] = [1, 2, 3]
dict["key"][0] = 5 // doesn't work
dict["key"]![0] = 5 // doesn't work
dict["key"] += 4 // uh uh
dict["key"]! += 4 // still no
dict["key"]!.append(4) // nope
如果您需要更改字典中的数组中的某些内容,则需要获取数组的副本,对其进行更改并重新分配,如下所示:
if var arr = dict["key"] {
arr.append(4)
dict["key"] = arr
}
ETA:相同的技术在 Swift beta 3 中有效,但常量数组不再允许更改内容。