I wonder if the following can be written shorter
var t = [String:[Int]]()
if t["a"] == nil { t["a"] = [1] }
else { t["a"]!.append(2) }
That is assigning a hash value if it does not exist and re-use it else.
I know I can write a function like
func extend(inout t:[String:[Int]], key:String, n:Int) {
if t[key] == nil { t[key] = [n] }
else { t[key]!.append(n) }
}
but wonder if there is a more elegant way.
Edit Actually I was looking for a shortcut for the function but copy/pasted test code above having different init/add values.
You can use the fact that optional chaining returns
nil
if the method could not be called:Implementation as a generic function (which operates on the optional dictionary value, not on the entire dictionary):
If you are trying to append
1
if the array exists, and create[1]
if the array doesn't exist (as implied by yourextend
function), you can use the nil coalescing operator??
like so:Extended example: