如何在 init() 期间使用 setter/getter?

问题描述 投票:0回答:1

我从来没有完全理解 init() 发生了什么。

有没有一种干净、简单的方法来实现我在下面的代码中尝试做的事情?

fileprivate struct Foo {
    
    var data: Int
    
    var twiceAsMuch: Int {
        set(value) {
            data = value / 2
        }
        get {
            data * 2
        }
        
    }
    
    init(twice: Int) {
        // The following line won't compile because
        // "Self used before all stored properties are initialized"
        self.twiceAsMuch = twice
    }
}
swift init
1个回答
0
投票

它告诉您,在执行“init”之前,计算变量所需的结构状态不会初始化。

这编译得很好:(我假设你希望在初始化器中划分初始值。

    fileprivate struct Foo {
    
    var data: Int
    
    var twiceAsMuch: Int {
        set(value) {
            data = value / 2
        }
        get {
            data * 2
        }
        
    }
    
    init(twice: Int) {
        // The following line won't compile because
        // "Self used before all stored properties are initialized"
        self.data = twice / 2
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.