重写属性观察器 [英] Override property observer

查看:74
本文介绍了重写属性观察器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我覆盖函数noise时,该函数将被新的替换.但是,当我用观察者覆盖属性时,旧值和新值都会同时执行.

When I override the function noise, the function gets replaced by the new one. But when I override a property with an observer, the old and new value gets both executed.

在操场上:

class Vehicle {
    func noise(sound: String) {
        println("Vehicle sound sounds like \(sound)")
    }
}

class Train: Vehicle {
    override func noise(sound: String) {
        println("A train does: \(sound)")
    }
}

输出:

var oldTrain = Train()
bulletTrain.noise("tjoek tjoek") // Prints: "A train does: tjoek tjoek"

但是当我对带有观察者的属性进行相同操作时:

But when I do the same with an property with an observer:

在操场上:

class Foo {
    var something: Int! {
        didSet {
            println("vroom")
        }
    }
}

class Bar: Foo {
    override var something: Int! {
        didSet {
            println("toot toot")
        }
    }
}

输出:

var foobar = Bar()
foobar.something = 3 // Prints: "vroom" & "toot toot"

那么我应该如何用观察者覆盖属性,以及如何防止执行旧值呢?

So how am I supposed to override a property with an observer and how to prevent the old values to be executed as well?

推荐答案

您可以覆盖属性的setget部分,并将println移到该属性中.这样,Swift不会调用原始代码-除非您调用super.

You can override the set and get part of the property and move your println there. This way Swift won't call the original code -- unless you call super.

class Foo {
    private var _something: Int!

    var something: Int! {
        get {
            return _something
        }
        set {
            _something = newValue
            println("vroom")
        }
    }
}

class Bar: Foo {
    override var something: Int! {
        get {
            return _something
        }
        set {
            _something = newValue
            println("toot toot")
        }
    }
}

那不是很好.

这是一个更好-更简单的解决方案:

Here's a better -- and simpler -- solution:

class Foo {
    var something: Int! {
        didSet {
            somethingWasSet()
        }
    }

    func somethingWasSet() {
        println("vroom")
    }
}

class Bar: Foo {
    override func somethingWasSet() {
        println("toot toot")
    }
}

由于没有办法覆盖" didSet,因此剩下的就是覆盖专门为此目的创建的辅助功能.

Since there is no way to "override" the didSet, what remains is overriding a secondary function especially created for that purpose.

这篇关于重写属性观察器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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