Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a dictionary with a mutable array as the value in Swift

I am trying to do this:

var dictArray = [String:[String]]()
dictArray["test"] = [String]()
dictArray["test"]! += "hello"

But I am getting the weird error NSString is not a subtype of 'DictionaryIndex<String, [(String)]>'.

I just want to be able to add objects to an array inside a dictionary.

Update: Looks like Apple considers this a "known issue" in Swift, implying it will work as expected eventually. From the Xcode 6 Beta 4 release notes:

...Similarly, you cannot modify the underlying value of a mutable optional value, either conditionally or within a force-unwrap:

tableView.sortDescriptors! += NSSortDescriptor(key: "creditName", ascending: true)

Workaround: Test the optional value explicitly and then assign the result back:

if let window = NSApplication.sharedApplication.mainWindow {
    window.title = "Currently experiencing problems"
}
tableView.sortDescriptors = tableView.sortDescriptors!
like image 372
devios1 Avatar asked Jul 20 '14 21:07

devios1


2 Answers

You can only do this

var dictArray = [String:[String]]()
dictArray["test"] = [String]()
var arr = dictArray["test"]!;
arr += "hello"
dictArray["test"] = arr

because dictArray["test"] give you Optional<[String]> which is immutable

  6> var test : [String]? = [String]()
test: [String]? = 0 values
  7> test += "hello"
<REPL>:7:1: error: '[String]?' is not identical to 'UInt8'

append also won't work due to the same reason, Optional is immutable

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

BTW the error message is horrible...

like image 83
Bryan Chen Avatar answered Oct 24 '22 04:10

Bryan Chen


You may use NSMutableArray instead of [String] as a value type for your dictionary:

var dictArray: [String: NSMutableArray] = [:]
dictArray["test"] = NSMutableArray()
dictArray["test"]!.addObject("hello")
like image 20
Pavel Kondratyev Avatar answered Oct 24 '22 03:10

Pavel Kondratyev