【问题标题】:How to override setter in Swift如何在 Swift 中重写 setter
【发布时间】:2016-07-26 05:40:26
【问题描述】:

超类:

class MySuperView : UIView{
    var aProperty ;
}

子类继承父类:

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

我想重写超类的属性的setter/getter方法,

如何在 Swift 中重写这个方法?请帮助我,谢谢。

【问题讨论】:

    标签: swift overriding setter getter


    【解决方案1】:

    你想用你的自定义设置器做什么?如果你想让类在设置值之前/之后做一些事情,你可以使用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
    

    控制台输出:

    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)
    

    控制台输出:

    0

    会将 aVar 从 0 设置为 5

    0

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 2019-01-07
    • 1970-01-01
    相关资源
    最近更新 更多