Reputation: 23
I'm not sure if I'm being an idiot or there is a compiler bug in the current Swift compiler but...
I declare a function into which I pass a Dictionary<String, String>
, in that method I attempt to add an item into the Dictionary
, the method is
func writeStatus(res: Dictionary<String, String>) {
res["key"] = "value"
}
and I get the compiler error
'@lvalue $T5 is not identical to '(String, String)'
In the method the Dictionary
is declared in i can add items fine. So my question is how to I add items into a dictionary in a function? I could do all this in the line function but I hate functions that do too much.
I am using the Swift compiler in Xcode 6.2 beta if that's any help.
Thanks
Upvotes: 0
Views: 49
Reputation: 7960
Not sure if this is more helpful, but if you want the dictionary to be mutated, it might be an idea to use an inout
argument:
func addDict(inout res: [String: String]) {
res["key"] = "value"
}
var res = [String: String]()
addDict(&res)
println(res) // [key: value]
This doesn't have any errors, and res
will have the values assigned to it in the addDict
function.
Upvotes: 1
Reputation: 15464
By default all function parameters are immutable. So if you try to mutate them you will get compiler error. If you want to mutate function parameter define it as var
.
func writeStatus(var res: [String: String]) {
res[key] = "value"
}
But here it will not work. Because Dictionary
is value type and value types are copied when they are passed into a function. And your mutation will only have affect on copied value. So in this senario defining parameter as inout
will solve your problem
Upvotes: 1