Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set objects to empty NSDictionary in Swift [duplicate]

I can create an NSDictionary

    var namesDictionary=Dictionary<String,String>()
    namesDictionary["Jacob"] = "Marry"

But, when I create a empty dictionary like coded below, line 1 i okie, but line 2 (adding values) throws an error.

    var namesDictionary =[:]
    namesDictionary["Jacob"] = "Marry"

Error is "Cannot assign to the result of this expression". Is there any other way to assign the values.

like image 353
NNikN Avatar asked Jun 29 '14 16:06

NNikN


1 Answers

It looks like it's an issue with swift interpreting the type of your dictionary. Try explicitly typing your empty dictionary.

var namesDictionary: Dictionary<String, String> = [:]
namesDictionary["Jacob"] = "Marry"

I think a better use for [:] is for emptying an already defined dictionary. If you add a third line namesDictionary = [:], you will be able to call namesDictionary["Jacob"] = "Marry" again since the compiler knows what type of dictionary it is from the inital declaration.

like image 55
Connor Avatar answered Oct 08 '22 06:10

Connor