超类:
class MySuperView : UIView{
var aProperty ;
}
子类继承超类:
class Subclass : MySuperClass{
// I want to override the aProperty's setter/getter method
}
我想覆盖超类的属性的setter / getter方法,
如何在Swift中覆盖此方法?请帮帮我,谢谢。
答案 0 :(得分:46)
您想对自定义设置器做什么?如果您希望课程在设置值之前/之后执行某些操作,则可以使用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
控制台输出:
将aVar从0设置为5
从0开始将aVar设置为5
但是,如果要完全更改setter与超类的交互方式:
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)
控制台输出:
0
将aVar从0设置为5
0