Lazy var giving 'Instance member can not be used on type' error

后端 未结 2 1350
情话喂你
情话喂你 2020-12-16 11:57

I had this error several times now and I resorted to different workarounds, but I\'m really curious why it happens. Basic scenario is following:

class SomeCl         


        
相关标签:
2条回答
  • 2020-12-16 12:36

    There are two requirements that are easily overlooked with lazy variables in Swift, and, unfortunately, the warnings are cryptic and don't explain how to fix it.

    Lazy Variable Requirements

    1. Use self.: When referring to instance members, you must use self.. (E.g. self.radius.)

      If you forget to use self., you'll get this error:

      Instance member 'myVariable' cannot be used on type 'MyType'

    2. Specify the type: The type cannot be inferred, it must be explicitly written. (E.g. : Float.)

      If you forget to specify the type, you'll get this error:

      Use of unresolved identifier 'self'

    Example

    struct Circle {
      let radius: Float
      lazy var diameter: Float = self.radius * 2 // Good
    //lazy var diameter        =      radius * 2 // Bad (Compile error)
    }
    
    0 讨论(0)
  • 2020-12-16 12:49

    Try that :

    class SomeClass {
      var coreDataStuff = CoreDataStuff!
      lazy var somethingElse: SomethingElse = SomethingElse(coreDataStuff: self.coreDataStuff)
    }
    

    It is important to precise the type of your lazy var and to add self. to the argument you pass

    0 讨论(0)
提交回复
热议问题