简体   繁体   中英

Inheritance of property methods (set, get, didSet, willSet, etc.) in Swift

My question is how to deal with inheritance of property methods such as set , get , didSet , willSet , ...?

Let's take an example: I want to override the setter method of a property in a Swift class. Here is what I want to achieve (which is obviously not working):

class A {
    var value: Int {get {...} set {...} }
}

class B: A {
    var value: Int {
        set(newValue) {
            // do some fancy stuff...
        }
    }
}

This is not working, too:

// in class B
override func setValue(newValue: Int) {
    // do some fancy stuff...
}

We can do in Swift something like this:

class A {
    var _value: Int = 0
    var value: Int {
        get {
            return _value
        }
        set {
            _value = newValue
        }
    }
}

class B: A {
    override var value: Int {
        get {
            return _value
        }
        set {
            _value = newValue + 1
        }
    }
}

let a = A()
a.value = 1
print(a.value) // => 1

let b = B()
b.value = 1 
print(b.value) // => 2

This approach is not very elegant because I have to implement also the getter methods, which is actually not necessary, because only the setter should be overridden.

You could do:

class A {
    var value: Int = 0
}

class B: A {
    override var value: Int {
        get { return super.value }
        set {
            // Something fancy...
            super.value = newValue
        }
    }
}

While you still have to implement a getter in B , you at least don't need _value , which helps keeps class A clean.

Unfortunately your only way to do this would be to create a separate get and set method if you really wanted to do this.

class A {
  private var value: Int = 0

 func getValue() -> Int { return value }
 func setValue(newValue : Int) {
   value = newValue
 }
}

By the nature of using computed properties you are basically doing a "shortcut" in some ways over making two separate methods - and as thus you would have to override both the set and get if you wanted to change things.

Depending on your usage an override of didSet could do the trick (based on your last example):

class B: A {
    override var value: Int {
        didSet {
            _value++
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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