Most optimal way to increment or initialize an Int in a Swift Dictionary

Update

Since Swift 4 you can use a default value in the subscript (assuming the dictionary has Value == Int):

dict[key, default: 0] += 1

You can read more about it in the Swift Evolution proposal Dictionary & Set Enhancements under Key-based subscript with default value


One way would be to use the nil coalescing operator:

dict[key] = ((dict[key] as? Int) ?? 0) + 1

If you know the type of the dictionary you can almost do the same but without casting:

dict[key] = (dict[key] ?? 0) + 1

Explanation:

This operator (??) takes an optional on the left side and a non optional on the right side and returns the value of the optional if it is not nil. Otherwise it returns the right value as default one.

Like this ternary operator expression:

dict[key] ?? 0
// is equivalent to
dict[key] != nil ? dict[key]! : 0

you can try this:

dict[key, default:0] += 1

When dict[key, default: 0] += 1 is executed with a value of key that isn’t already a key in key, the specified default value (0) is returned from the subscript, incremented, and then added to the dictionary under that key.

see apple documentation

Tags:

Swift