我想这样做:
var dictArray = [String:[String]]() dictArray["test"] = [String]() dictArray["test"]! += "hello"
但我得到了奇怪的错误NSString不是’DictionaryIndex< String,[(String)]>‘的子类型.
我只是希望能够将对象添加到字典中的数组中.
更新:看起来Apple认为这是Swift中的“已知问题”,暗示它最终将按预期工作.来自Xcode 6 Beta 4发行说明:
…Similarly,you cannot modify the underlying value of a mutable
optional value,either conditionally or within a force-unwrap:06001
Workaround: Test the optional value explicitly and then assign the
result back:06002
你只能这样做
var dictArray = [String:[String]]() dictArray["test"] = [String]() var arr = dictArray["test"]!; arr += "hello" dictArray["test"] = arr
因为dictArray [“test”]给你Optional< [String]>这是不可改变的
6> var test : [String]? = [String]() test: [String]? = 0 values 7> test += "hello" <REPL>:7:1: error: '[String]?' is not identical to 'UInt8'
由于同样的原因,append也不会工作,Optional是不可变的
3> dictArray["test"]!.append("hello") <REPL>:3:18: error: '(String,[(String)])' does not have a member named 'append' dictArray["test"]!.append("hello") ^ ~~~~~~
BTW错误信息很可怕……