如何在Swift中重写二传手 [英] How to override setter in Swift

查看:80
本文介绍了如何在Swift中重写二传手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

超类:

class MySuperView : UIView{
    var aProperty ;
}

子类继承超类:

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

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

I want to override the superclass's property's setter/getter method ,

如何在Swift中重写此方法?请帮助我,谢谢.

how to override this method in Swift ? Please help me , thanks .

推荐答案

您要如何使用自定义设置器?如果要让类在设置值之前/之后执行某些操作,则可以使用willSet/didSet:

What do you want to do with your custom setter? If you want the class to do something before/after the value is set, you can use 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:

将aVar从0设置为5

WillSet aVar to 5 from 0

did将aVar从0设置为5

didSet aVar to 5 from 0

但是,如果您想完全更改设置器与超类的交互方式:

If, however, you want to completely change how the setter interacts with the superclass:

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

将aVar从0设置为5

Would have set aVar to 5 from 0

0

这篇关于如何在Swift中重写二传手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆