MikeMaus
MikeMaus

Reputation: 405

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]

Upvotes: 1

Views: 189

Answers (2)

Rob Napier
Rob Napier

Reputation: 299265

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]

Upvotes: 5

zeytin
zeytin

Reputation: 5643

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.

Upvotes: 2

Related Questions