Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 883
alex Avatar asked Sep 17 '25 12:09

alex


1 Answers

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")
like image 106
Code Different Avatar answered Sep 19 '25 07:09

Code Different