Say I have a map of keys to arrays of values and want to add a value to one of these arrays:
func addVal<K:Hashable, V>(map: inout [K: [V]], new: (key: K, val: V)) {
if var list = map[new.key] {
list.append(new.val)
} else {
map[new.key] = [new.val]
}
}
This code won't work: since arrays have value semantics, list
is a copy of map[new.key]
and the new value never gets inserted into the stored array.
Is there a nice, idiomatic way to to this?
I am aware that this works perfectly:
func addVal<K:Hashable, V>(map: inout [K: [V]], new: (key: K, val: V)) {
if map[new.key] != nil {
map[new.key].append(new.val)
} else {
map[new.key] = [new.val]
}
}
I'd consider this a non-nice workaround, though; I'd rather deal with optionals without checking explicitly for nil
.