alex
alex

Reputation: 4924

How do I update a dictionary key in swift?

I am trying to make a two column table with Model name and price. Each model can be edited and saved (see also). For this I think I need a dictionary:

var models = ["iPhone 6 plusss Gold 128 GB" : 1000,"iPhone 6 Plus Gold 64 GB" : 500, "iPhone 6 Gold 128 GB" : 250, "iPhone 6 Gold 16 GB" : 100]

But I'd like to update the key 0 because I misspelled "plusss", for example. How can I do this?

I found how you can update a key value pair:

models.updateValue(200, forKey: "iPhone 6 Gold 16 GB")

But how do I update a key?

[EDIT] apparently i am "thinking" about it in wrong way. I am reading up on dictionaries and i think the best way is to go with a class (like vadian comments)

Upvotes: 4

Views: 9772

Answers (3)

Legenda_759
Legenda_759

Reputation: 7

var models = ["iPhone 6 plusss Gold 128 GB" : 1000,"iPhone 6 Plus Gold 64 GB" : 500, "iPhone 6 Gold 128 GB" : 250, "iPhone 6 Gold 16 GB" : 100]
models["iPhone 6 plus Gold 128 GB"] = models.removeValue(forKey: "iPhone 6 plusss Gold 128 GB") //"iPhone 6 plus Gold 128 GB" : 1000

Upvotes: 1

Code Different
Code Different

Reputation: 93191

You cannot change a key but you can remove the existing key and add a new one:

extension Dictionary {
    mutating func changeKey(from: Key, to: Key) {
        self[to] = self[from]
        self.removeValueForKey(from)
    }
}

var models = ["iPhone 6 plusss Gold 128 GB" : 1000,"iPhone 6 Plus Gold 64 GB" : 500, "iPhone 6 Gold 128 GB" : 250, "iPhone 6 Gold 16 GB" : 100]
models.changeKey("iPhone 6 plusss Gold 128 GB", to: "iPhone 6 plus Gold 128 GB")

Upvotes: 7

Access Denied
Access Denied

Reputation: 9501

In Swift, the dictionary requires keys to confirm to a Hashable protocol. So in order to change key you need to delete previous entry and add a new one. You can't change key, since entry may go to another bucket. It will be necessary to lookup the old entry delete it and insert new one anyway. For more info, how hashtables work take a look at the following thread How does a hash table work?

Upvotes: 6

Related Questions