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

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

The type of the dictionary is Dictionary, but by design the value type for this key will always be Int as it will 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
        }

      

+4


source to share


3 answers


Refresh

Since Swift 4, you can use the default subscript (assuming the dictionary has it Value == Int

):

dict[key, default: 0] += 1

      

You can read more about this in the Swift Evolution Sentence Dictionary & Set Extensions under Main Index with default


One way is to use the nil concatenation operator:

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

      



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

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

      

Explanation :

This operator ( ??

) takes an optional parameter on the left and an optional parameter on the right, and returns the value of the optional parameter if not equal nil

. Otherwise, it returns the correct value as the default.

Like this ternary operator expression:

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

      

+8


source


You can try this:

dict[key, default:0] += 1

      



When dict[key, default: 0] += 1

executed with a key value that is not yet a key in the key, the specified default value (0) is returned from the index, incremented by one, and then added to the dictionary under that key.

see Apple documentation

+4


source


A more readable style would be:

if let v = dict[key] as? Int {
    dict[key] = v + 1
} else {
    dict[key] = 0
}

      

0


source







All Articles