1

I don't know the datatypes ahead of time, how can I add data to the empty dictionary without types. Looks like someone asked the same question here but no answer was accepted How to create Dictionary that can hold anything in Key? or all the possible type it capable to hold

Swift Compiler Error:

Cannot assign to the result of this expression.

I get this error in b["test"] = 23 this line.

var a = [String:Int]()
a["test"] = 23  # Works 


var b = [:]
b["test"] = 23 # Compiler Error
Community
  • 1
  • 1
aarti
  • 2,815
  • 1
  • 23
  • 31

3 Answers3

1

In your example, b is of type NSDictionary, which is immutable. Therefore you get an error when trying to modify its contents.

You need to declare b as an NSMutableDictionary to make this work:

let dictionary: NSMutableDictionary = [:]
dictionary["key"] = "value" // No errors.
ABakerSmith
  • 22,759
  • 9
  • 68
  • 78
1

You can declare you second dictionary as a Swift dictionary as well, but with AnyObject as the value type:

var b = [String:AnyObject]()

Then you can do:

b["test"] = 23
b["stuff"] = "hello world"

This value will be of type AnyObject, so you have to cast it back when you retrieve it:

let result = b["test"] as! Int
let sentence = b["stuff"] as! String

or

if let result = b["test"] as? Int {
    // use result (23)
}
if let sentence = b["stuff"] as? String {
    // use sentence ("hello world")
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • I have to define the key as String, When I try to define var d = [AnyObject:AnyObject](), I get an error 'AnyObject' does not conform to protocol 'Hashable' – aarti May 03 '15 at 20:23
  • 1
    @classyhacker you need to define it as NSObject:AnyObject you should always use Swift native dictionary – Leo Dabus May 03 '15 at 21:18
1
var b:[NSObject:AnyObject] = [:]
b["test"] = 23
b[1] = "one"
b // ["test": 23, 1: "one"]
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571