swiftswift-dictionary

Nil coalescing operator for dictionary


Trying to access/ check the key in dictionary and add values.

myDict["Algebra"] initially returns nil. Why "nil coalescing" doesn't work here?

var myDict = [String : [Int]]()
myDict["Algebra"]?.append(contentsOf: [98,78,83,92]) ?? myDict["Algebra"] = [98,78,83,92]

Solution

  • Trying use like yours give you and error : Left side of mutating operator has immutable type '[Int]?'

    By putting parentheses it will be no compile error and it will work

    var myDict = [String : [Int]]()
    myDict["Algebra"]?.append(contentsOf: [98,78,83,92]) ?? (myDict["Algebra"] = [98,78,83,92])
    print(myDict) // ["Algebra": [98, 78, 83, 92]]
    

    Swift Documentation is here for Infix Operators.