Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 SomeClass {   var coreDataStuff = CoreDataStuff!   lazy var somethingElse = SomethingElse(coreDataStuff: coreDataStuff) } 

So I understand I can not use self before class is fully initialised, but in this case I'm using self property coreDataStuff to initialise a lazy var which will not happen until my instance is ready.

Anybody could explain me why I'm getting Instance member can not be used on type error?

like image 512
66o Avatar asked Dec 11 '15 14:12

66o


People also ask

Which one of the key Cannot be used with instance variable?

Instance Variable cannot have a Static modifier as it will become a Class level variable. Meaning STATIC is one of the keyword which cannot be used with Instance variable.

What is instance member in Swift?

Unless otherwise specified, a member declared within a class is an instance member. So instanceInteger and instanceMethod are both instance members. The runtime system creates one copy of each instance variable for each instance of a class created by a program.


2 Answers

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

like image 114
Tancrede Chazallet Avatar answered Jan 02 '23 22:01

Tancrede Chazallet


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) } 
like image 33
Senseful Avatar answered Jan 03 '23 00:01

Senseful