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

1
  • 2
    Tip: You should never do this in Swift if (dictKeyVal != nil). Commented Nov 22, 2018 at 10:17

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Default should be [m]
@JoakimDanielson nope, that would result in dic[key] = [m,m] instead of the desired dic[key] = [m] in case there was no value for key.
Sorry, now I get it. Neat solution btw.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.