swiftinit

how to use setter/getters during init()?


I've never quite grasped what's going on with init().

Is there a clean, simple way to achieve what I'm trying to do in the code below ?

Edit: I'd like to avoid duplicating the data = value / 2 logic, because it might be significantly more complex than this simple example. I also don't want to provide a default value for data or make it optional because I want a compile-time guarantee that data is initialized.

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
    }
}

Solution

  • Edited. This method only works if the calculation does not depend on instance variables.

    It's telling you that until "init" has executed, the struct state required for the computed variable is not initialized.

    This compiles just fine: (I assumed you wished to divide the initial value inside the initializer.

        
    fileprivate struct Foo {
        
        var data: Int
        static private func twiceAsMuch(_ v: Int) -> Int { v / 2 }
        var twiceAsMuch: Int {
            set(value) {
                data = Self.twiceAsMuch(value)
            }
            get {
                data * 2
            }
        }
        
        init(twice: Int) {
            self.data = Self.twiceAsMuch(twice)
        }
    }