ios - Cannot use instance member within property initializer, setting the variable to lazy doesn't work -




other questions point out use lazy before variable, doesn't seem work in case.

i still error,

cannot use instance member 'defaults' within property initializer; property initializers run before 'self' available

where getting wrong ?

class userdata{      let defaults        = userdefaults.standard     lazy var userdatadict    = defaults.object(forkey: "userdatadict") as? [string: string] ?? [string: string]()       static func setmobilenumber(mobilenumber: string){          userdatadict["mobilenumber"]         =   mobilenumber      } } 

try syntax:

lazy var userdatadict: [string : string] = {      defaults.object(forkey: "userdatadict") as? [string: string] ?? [string: string]() }() 

however, set userdatadict once (the first time accessed), , won't see changes/updates done userdefaults.standard after that.

i recommend use computed property instead:

var userdatadict: [string : string] {      guard let dict = defaults.object(forkey: "userdatadict") as? [string: string] ?? [string: string]() else {         return [:]     }     return dict } 

(it isn't such costly operation lazily once, anyway)

also, don't see point in having copy of userdefaults.standard property of object; perhaps it's best have:

// remove:  // let defaults = userdefaults.standard  var userdatadict: [string : string] {     guard let dict = userdefaults.standard.object(forkey: "userdatadict") as? [string: string] ?? [string: string]() else {         return [:]     }     return dict } 

as last temark, these amkes dictionary "read only" far user defaults database concerned; if wish preserve changes, property needs setter too:

var userdatadict: [string : string] {     {         guard let dict = userdefaults.standard.object(forkey: "userdatadict") as? [string: string] ?? [string: string]() else {         return [:]         }         return dict     }     set (newvalue) {         userdefaults.standard.set(newvalue, forkey: "userdatadict")         userdefaults.standard.synchronize()     } } 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -