超类:
class MySuperView : UIView{ var aProperty ; }
一个子类继承超类:
class Subclass : MySuperClass{ // I want to override the aProperty's setter/getter method }
如何在Swift中覆盖此方法?请帮助我,谢谢.
你想用自定义设置器做什么?如果您希望该类在设置值之前/之后执行某些操作,则可以使用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与超类的交互方式:
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