Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use instance member 'getA' within property initializer; property initializers run before 'self' is available [duplicate]

Y this giving this error - Cannot use instance member 'getA' within property initializer; property initializers run before 'self' is available

class A  {

    var asd : String  = getA()

    func getA() -> String {
        return "A"

    }
}
like image 449
vaibby Avatar asked Dec 11 '18 12:12

vaibby


2 Answers

Property initializer run before self is available.

The solution is to lazy initialize the property:

class A {
    lazy var asd: String  = getA()

    func getA() -> String {
        return "A"
    }
}

That will initialize the property first time you are trying to use it.

like image 154
ppalancica Avatar answered Sep 28 '22 04:09

ppalancica


You first need to initialize your asd variable. Then in the init you can apply your function value to it.

class A  {
var asd : String = ""

init() {
    self.asd = self.getA()
}

func getA() -> String {
    return "A"

} }
like image 41
Jonathan Avatar answered Sep 28 '22 02:09

Jonathan