J_llama J_llama - 3 months ago 13
Swift Question

Variable with getter/setter cannot have initial value, on overridden stored property

When creating a stored property with Observing Accessors, I can specify a default value. However, when overriding a stored property and its Accessors I cannot specify a default value.


Variable with getter/setter cannot have initial value.


Which seems very strange, as this is NOT a computed property with a getter/setter, but a set of Observing Accessors on a stored property!

class FirstViewController: UIViewController {

internal var test: Float = 32.0 {
willSet {

}

didSet {

}
}


The first view controller compiles fine, with a stored property initialized to 32.0

class SecondViewController: FirstViewController {

override var test: Float = 64.0 {
willSet {

}

didSet {

}
}


The second view controller does not compile, as the 'computed property' is being given an initial value

Answer

In swift you are able to override properties only with computed properties (which are not able to have default values) with same type. In your case, if you wish override test property in SecondViewController you need write something like this:

override var test: Float {
    get {
        return super.test
    }
    set {
        super.test = newValue
    }
}

And there is no way to override didSet/willSet observers directly; you may do this by write other methods invoked in observers and just override them:

FirstViewController:

internal var test: Float = 32.0 {
    willSet {
        test_WillSet(newValue)
    }
    didSet {
        test_DidSet(oldValue)
    }
}

func test_WillSet(newValue: Float) {}
func test_DidSet(oldValue: Float) {}

SecondViewController:

override func test_WillSet(newValue: Float) {
    super.test_WillSet(newValue)
}
override func test_DidSet(oldValue: Float) {
    super.test_DidSet(oldValue)
}