Set objects to empty NSDictionary in Swift
21,319
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.
Author by
NNikN
Updated on June 30, 2020Comments
-
NNikN almost 4 years
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.
-
NNikN almost 10 yearsThen it should have thrown error in the first line itself.
-
Connor almost 10 yearsThe first line is fine. It creates an empty dictionary, but the key/ value types aren't Strings. The dictionary at this point is pretty much useless since it won't accept any key value pairs
-
NNikN almost 10 yearsOkie, what is the difference between the var namesDictionary=Dictionary<String,String>() and var namesDictionary: Dictionary<String, String> = [:]
-
Connor almost 10 yearsPretty much just syntactic sugar. Both create an empty Dictionary<String, String>
-
NNikN almost 10 yearsnamesDictionary.setValue("Marry", forKey: "Jacob") works
-
Connor almost 10 yearssetValueForKey: is part of NSKeyValueCoding, not specific to dictionaries. If you call
namesDictionary["jacob"]
after it, you'll see it hasn't changed the dictionary