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.

Share:
21,319
NNikN
Author by

NNikN

Updated on June 30, 2020

Comments

  • NNikN
    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
    NNikN almost 10 years
    Then it should have thrown error in the first line itself.
  • Connor
    Connor almost 10 years
    The 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
    NNikN almost 10 years
    Okie, what is the difference between the var namesDictionary=Dictionary<String,String>() and var namesDictionary: Dictionary<String, String> = [:]
  • Connor
    Connor almost 10 years
    Pretty much just syntactic sugar. Both create an empty Dictionary<String, String>
  • NNikN
    NNikN almost 10 years
    namesDictionary.setValue("Marry", forKey: "Jacob") works
  • Connor
    Connor almost 10 years
    setValueForKey: is part of NSKeyValueCoding, not specific to dictionaries. If you call namesDictionary["jacob"] after it, you'll see it hasn't changed the dictionary