Nil coalescing operator for dictionary

183 Views Asked by At

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]
2

There are 2 best solutions below

0
zeytin On BEST ANSWER

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.

0
Rob Napier On

While this works with parentheses, the problem you're trying to solve is exactly what the default subscript does, without abusing the ?? operator into an implicit if statement with side-effects:

myDict["Algebra", default: []].append(contentsOf: [98,78,83,92])

You may also find this syntax a little clearer:

myDict["Algebra", default: []] += [98,78,83,92]