4

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)

alex
  • 4,804
  • 14
  • 51
  • 86
  • 1
    It might be easier to use this syntax with fixed keys : `var models = [{"name" : "iPhone 6 plusss Gold 128 GB", "price" : 1000},{"name" : "iPhone 6 Plus Gold 64 GB", "price" : 500`}] or still better a custom `struct` or `class` – vadian Oct 17 '15 at 12:17
  • I beleive you should delete old entry and add new entry. – Access Denied Oct 17 '15 at 12:17
  • 1
    I assume that dictionary in swift works like hashtables and you can't change key, since entry will go to another bucket. – Access Denied Oct 17 '15 at 12:20

3 Answers3

6

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?

Community
  • 1
  • 1
Access Denied
  • 8,723
  • 4
  • 42
  • 72
  • 3
    From the [documentation](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/index.html#//apple_ref/occ/cl/NSMutableDictionary) Use `NSMutableDictionary`'s `setObject:forKey:` and `removeObjectForKey:` – Arc676 Oct 17 '15 at 12:31
6

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")
Code Different
  • 90,614
  • 16
  • 144
  • 163
1
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
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103