UpdateValue does not work for dictionary

I am building a test application using Swift in Xcode, and I ran into an annoying problem. I am writing a simple class that will act like a cache using a Dictionary object. My implementation is below:

import Foundation import UIKit class ImageCache { var dict:Dictionary<String,NSData>?; init() { dict = Dictionary<String,NSData>(); } func exists(id:String) -> Bool { return dict!.indexForKey(id)!==nil; } func getImage(id:String) -> UIImage? { if(!exists(id)) { return nil; } return UIImage(data: (dict!)[id]); } func setData(id:String, data:NSData) { dict!.updateValue(data, forKey: id); } } 

The problem is with the latter method, with Xcode stating: "Could not find UpdateValue member." This is strange because the code hint seems to show it just fine:

Code hint

But when I try to compile:

Compilation error

Could this be a bug in Xcode? Or am I missing something super-obvious?

+5
dictionary ios xcode swift
source share
2 answers

this is not a bug or a quirk in the compiler.

Optional (which may or may not be erroneous)

what happened is that Optional stores the Dictionary as an immutable object (possibly with let ). Thus, even Optional it is changed, you cannot directly modify the basic Dictionary object (without overriding the Optional object).

updateValue(forKey:) is a mutation method, you cannot call it an immutable object and therefore an error.

you can get around this by doing

 var d = dict! d.updateValue(data, forKey: id) 

because you are copying the dictionary into another mutable variable, which is then modified and can call the mutation method on it

but without dict = d , your change will not apply to dict , because Dictionary is a value type, it makes a copy with each assignment

related answer

+2
source share

It smells like an error or a quirk in the compiler.

I just tried something like

 var d = dict! d.updateValue(data, forKey: id) 

and works as expected.

+2
source share

All Articles