ios - updateValue not working for Dictionary -


i'm creating test app using swift in xcode, , i've run annoying issue. i'm writing simple class act cache using dictionary object. implementation 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 issue in last method, xcode stating "could not find member 'updatevalue'". weird, because code hint seems show fine:

code hint

but when try compile:

compilation error

could potentially bug in xcode? or missing super-obvious?

this not bug or quirk in compiler.

it how optional implemented (which may flawed or not)

what happened optional store dictionary immutable object (with let perhaps). optional mutable, can't modify underlying dictionaryobject directly (without reassign optional object).

updatevalue(forkey:) mutating method, can't call on immutable object , hence error.

you can workaround doing

var d = dict! d.updatevalue(data, forkey: id) 

because copy dictionary mutable variable, mutable , able call mutating method on it

but without dict = d, change won't applied on dict because dictionary value type, makes copy on every assignment

related answer


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -