5

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"

    }
}
vaibby
  • 1,255
  • 1
  • 9
  • 23

2 Answers2

8

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.

ppalancica
  • 4,236
  • 4
  • 27
  • 42
2

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"

} }
Jonathan
  • 330
  • 2
  • 12