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

妖精的绣舞 提交于 2019-12-14 03:49:58

问题


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"

    }
}

回答1:


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.




回答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"

} }


来源:https://stackoverflow.com/questions/53724345/cannot-use-instance-member-geta-within-property-initializer-property-initiali

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!