How can I easily add elements to an array inside a dictionary?
It\'s always complaining with could not find member \'append\' or could not find an overloa
Here is what I was telling Nate Cook, in the comments for his quality answer. This is what I consider "easily [adding] elements to an array inside a dictionary":
dict["key"] = dict["key"]! + 4
dict["key"] = dict["key"] ? dict["key"]! + 4 : [4]
For now, we need to define the + operator ourselves.
@infix func +(array: T[], element: T) -> T[] {
var copy = array
copy += element
return copy
}
I think this version removes too much safety; maybe define it with a compound operator?
@infix func +(array: T[]?, element: T) -> T[] {
return array ? array! + element : [element]
}
dict["key"] = dict["key"] + 4
Finally, this is the cleanest I can get it, but I'm confused about how array values/references work in this example.
@assignment func +=(inout array: T[]?, element: T) {
array = array + element
}
dict["key"] += 5