是否可以将带有可变数组的字典作为Swift中的值

dev*_*os1 8 dictionary swift

我想这样做:

var dictArray = [String:[String]]()
dictArray["test"] = [String]()
dictArray["test"]! += "hello"
Run Code Online (Sandbox Code Playgroud)

但我得到了奇怪的错误NSString is not a subtype of 'DictionaryIndex<String, [(String)]>'.

我只是想能够将对象添加到字典中的数组中.

更新:看起来Apple认为这是Swift中的"已知问题",暗示它最终将按预期工作.来自Xcode 6 Beta 4发行说明:

...同样,您无法有条件地或在强制解包内修改可变可选值的基础值:

tableView.sortDescriptors! += NSSortDescriptor(key: "creditName", ascending: true)
Run Code Online (Sandbox Code Playgroud)

解决方法:显式测试可选值,然后返回结果:

if let window = NSApplication.sharedApplication.mainWindow {
    window.title = "Currently experiencing problems"
}
tableView.sortDescriptors = tableView.sortDescriptors!
Run Code Online (Sandbox Code Playgroud)

Bry*_*hen 10

你只能这样做

var dictArray = [String:[String]]()
dictArray["test"] = [String]()
var arr = dictArray["test"]!;
arr += "hello"
dictArray["test"] = arr
Run Code Online (Sandbox Code Playgroud)

因为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'
Run Code Online (Sandbox Code Playgroud)

append由于同样的原因也不会起作用,Optional是不可改变的

  3> dictArray["test"]!.append("hello")
<REPL>:3:18: error: '(String, [(String)])' does not have a member named 'append'
dictArray["test"]!.append("hello")
                 ^ ~~~~~~
Run Code Online (Sandbox Code Playgroud)

BTW错误信息太可怕了......

  • 这慢慢地杀了我 (3认同)