0

I currently have this code:

var dic = [String: [String]]() 

if (dic.index(forKey: key) != nil){
    dic[key]?.append(m)
}
else {
    dic[key] = [m]
}

However, in dic.index(forKey: key) and dic[key]?.append(m) I calculate the key twice.

Is there a possibility to do something like this?:

var dictKeyVal = &dic[key]
if (dictKeyVal != nil) {
    dictKeyVal?.append(m)
}
else {
    dic[key] = [m]
} 

where I get the reference to array at key or nil if there is no key

Martin Perry
  • 9,232
  • 8
  • 46
  • 114

1 Answers1

5

You can simply use a default value for the subscript and your whole code will be simplified to this:

var dic = [String: [String]]()
dic[key, default: []].append(m)
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116