ios - Lazy loading optional property that maybe nil later -


in objective-c, lazy init, can set @property nil , re-created when call getter.

however, in swift, lazy modifier, doesn't work .
tested code:

class someclass {     lazy var optionalvar: string? = {         return "abc"     }()      func checkvar() {         println(optionalvar!)     } }  let instance = someclass() instance.checkvar() //instance.variable = nil instance.checkvar() 

when variable set nil, not re-initialized. therefore, next line of code triggers run-time error.

how can make swift code works in objective-c ?
thanks.

----------------
edit: add more code

class someclass {     var optionalvar: string?      func checkvar() {         println(optionalvar!)     }      func createvar() -> string {         if let tempvar = optionalvar {             return tempvar         } else {             println("create optional")             return "123"         }     } }  let instance = someclass() instance.optionalvar = instance.createvar() instance.checkvar() instance.optionalvar = nil instance.optionalvar = instance.createvar() instance.checkvar() 

besides suggested in this answer, elegant alternate solution can propose intercept when property set nil, , override assignment default value:

class someclass {     private var _optionalvar: string?      var nonoptionalvar: string? {         { return _optionalvar }         set { _optionalvar = newvalue == nil ? "123" : newvalue }     }      init() {         self.nonoptionalvar = nil     } } 

there 1 downside though: have remember explicitly set property nil in initializer (otherwise property left @ default initial value, nil)


Comments

Popular posts from this blog

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -