超类:
class MySuperView : UIView{ var aProperty ; }@H_502_3@一个子类继承超类:
class Subclass : MySuperClass{ // I want to override the aProperty's setter/getter method }@H_502_3@我想覆盖超类的属性的setter / getter方法, @H_502_3@如何在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
@H_502_3@Console Output: @H_502_3@WillSet aVar to 5 from 0 @H_502_3@didSet aVar to 5 from 0@H_502_3@但是,如果您想完全改变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)
@H_502_3@Console output: @H_502_3@0 @H_502_3@Would have set aVar to 5 from 0 @H_502_3@0