Reputation: 953
I am writing an iPhone app in Swift. I have a dictionary that maps String keys to [MyClass] values. I have a function that does the following:
func addItem(object: MyClass) -> Bool {
if self.dict[object.name] == nil {
self.dict[object.name] = [MyClass]()
}
var objectList = self.dict[object.name]!
// Other code here that doesn't matter
objectList.append(object)
return true
}
The problem here is that when I reach the return statement, "objectList" has a count of 1, but self.dict[object.name]! has a count of 0. That is to say that objectList is actually a copy of the array in the dictionary rather than the same array.
I guess that makes some sense, since arrays are value types in Swift, but it's pretty inconvenient. Does anyone have a good solution for this? Can I force the return from the dictionary to a reference a la inout? Or do I need to create my own list class to wrap arrays with or save modified arrays back to the dictionary?
Upvotes: 2
Views: 227
Reputation: 93276
You need to append it to the array inside the dictionary:
self.dict[object.name]!.append(object)
What's happening is that a Dictionary instance's subscript
returns an Optional, since there's no guarantee that the dictionary actually has a value for the key you pass in. You can assign through either of the unwrapping operators (?
or !
) - in this case the force unwrapping is okay since you test and create the array above.
Upvotes: 2