如何覆盖Swift中的setter

前端之家收集整理的这篇文章主要介绍了如何覆盖Swift中的setter前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
超类:
class MySuperView : UIView{
    var aProperty ;
}

一个子类继承超类:

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

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

如何在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

原文链接:https://www.f2er.com/swift/318782.html

猜你在找的Swift相关文章