如何覆盖 Swift 中的 setter

How to override setter in Swift

超级class :

class MySuperView : UIView{
    var aProperty ;
}

子class 继承父class :

class Subclass : MySuperClass{
    // I want to override the aProperty's setter/getter method
}

我想覆盖超级class的属性的setter/getter方法,

如何在 Swift 中覆盖此方法?请帮助我,谢谢。

你想用你的自定义 setter 做什么?如果你想让 class 做一些事情 before/after 设置值,你可以使用 willSet/didSet:

class TheSuperClass { 
   var aVar = 0 
} 

class SubClass: TheSuperClass { 
     override var aVar: Int { 
         willSet { 
            print("WillSet aVar to \(newValue) from \(aVar)") 
        } 
        didSet { 
            print("didSet aVar to \(aVar) from \(oldValue)") 
        } 
    } 
} 


let aSub = SubClass()
aSub.aVar = 5

Console Output:

WillSet aVar to 5 from 0

didSet aVar to 5 from 0

但是,如果您想完全改变 setter 与 superclass 的交互方式:

class SecondSubClass: TheSuperClass { 
     override var aVar: Int { 
        get {
            return super.aVar
        }
        set { 
            print("Would have set aVar to \(newValue) from \(aVar)") 
        } 
    } 
} 

let secondSub = SecondSubClass()
print(secondSub.aVar)
secondSub.aVar = 5
print(secondSub.aVar)

Console output:

0

Would have set aVar to 5 from 0

0