Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

Given a directory and a key, I want to increment the value of that key if it exist in the dictionary, or initialize it to 1.

The dictionary type is Dictionary, but by design the value type for this key will always be an Int since it would only be changed by this code.

The code I have so far is below, but would like to optimize it, in swift style.

let v = dict[key] as? Int
if v != nil {
    dict[key] = v! + 1
} else {
    dict[key] = 1
}
like image 547
Droopycom Avatar asked Aug 08 '15 23:08

Droopycom


1 Answers

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
like image 197
Qbyte Avatar answered Oct 07 '22 14:10

Qbyte