简体   繁体   English

Swift:在init中调用self方法

[英]Swift: Call self method inside init

I want to implement something like this: 我想实现这样的事情:

class A {
    var a, b, c, d: Int

    init() {
        reset()
    }

    func reset() {
        a = 1
        b = 2
        c = 3
        d = 4
    }

    func blablabla() { 
        ...
    }
}

which cannot get compiled, error message: 无法编译,错误消息:

Variable "self.a" used before being initialized 初始化之前使用的变量“ self.a”

It doesn't make sense that I will have to copy the code from reset() into init() . 我必须将代码从reset()复制到init()

Is it a defect or is there another way to do it? 这是缺陷还是有其他解决方法?

No, it's not a defect, simply self cannot be referenced in an initializer until all stored properties have been initialized, and a super class initializer has been invoked (if any). 不,这不是缺陷,在所有存储的属性都已初始化并且调用了超类初始化器(如果有)之前,不能在初始化器中引用self

In your case it seems legit to do the initializations in a method, and call that from the initializer, but unfortunately it doesn't work. 在您的情况下,在方法中进行初始化并从初始化程序中调用它似乎是合法的,但是不幸的是,它不起作用。

Possible solutions: 可能的解决方案:

  • make the properties optional or implicitly unwrapped (discouraged, unless you really need them optionals) 使属性为可选或隐式解包(不推荐使用,除非您确实需要可选)
  • initialize the properties with fake values before calling reset : 在调用reset之前,用假值初始化属性:

     init() { self.a = 0 self.b = 0 self.c = 0 self.d = 0 reset() } 

    or 要么

     var a = 0 var b = 0 var c = 0 var d = 0 init() { reset() } 

提供a,b,c和d默认值,尤其是如果您要立即更改它们时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM