在 Swift 中覆盖具有不同类型的超类属性 [英] Overriding superclass property with different type in Swift

查看:40
本文介绍了在 Swift 中覆盖具有不同类型的超类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中,有人可以解释如何使用从原始属性子类化的另一个对象覆盖超类上的属性吗?

In Swift, can someone explain how to override a property on a superclass's with another object subclassed from the original property?

举个简单的例子:

class Chassis {}
class RacingChassis : Chassis {}

class Car {
    let chassis = Chassis()
}
class RaceCar: Car {
    override let chassis = RacingChassis() //Error here
}

这给出了错误:

Cannot override with a stored property 'chassis'

如果我将机箱改为var",则会出现错误:

If I have chassis as 'var' instead, I get the error:

Cannot override mutable property 'chassis' of type 'Chassis' with covariant type 'RacingChassis'

我在覆盖属性"下的指南中唯一能找到的内容表明我们必须覆盖 getter 和 setter,这可能适用于更改属性的值(如果它是var"),但是如何更改属性类?

The only thing I could find in the guide under "Overriding Properties" indicates that we have to override the getter and setter, which may work for changing the value of the property (if it's 'var'), but what about changing the property class?

推荐答案

Swift 不允许您更改任何变量或属性的类类型.相反,您可以在处理新类类型的子类中创建一个额外的变量:

Swift does not allow you to change the class type of any variables or properties. Instead you can create an extra variable in the subclass that handles the new class type:

class Chassis {}
class RacingChassis : Chassis {}

class Car {
    var chassis = Chassis()
}
class RaceCar: Car {
    var racingChassis = RacingChassis()
    override var chassis: Chassis {
        get {
            return racingChassis
        }
        set {
            if let newRacingChassis = newValue as? RacingChassis {
                racingChassis = newRacingChassis
            } else {
                println("incorrect chassis type for racecar")
            }
        }
    }
}

似乎无法使用 let 语法声明属性并在其子类中使用 var 覆盖它,反之亦然,这可能是因为超类实现可能不希望该属性在初始化后发生更改.因此,在这种情况下,需要在超类中使用var"声明该属性,以匹配子类(如上面的代码片段所示).如果无法更改超类中的源代码,那么最好在每次底盘需要变异时销毁当前 RaceCar 并创建一个新 RaceCar.

It seems one cannot declare a property with the let syntax and override it with var in it’s subclass or vice-versa, which may be because the superclass implementation might not be expecting that property to change once initialized. So in this case the property needs to be declared with ‘var’ in the superclass as well to match the subclass (as shown in the snippet above). If one cannot change the source code in the superclass then its probably best to destroy the current RaceCar and create a new RaceCar every time the chassis needs to be mutated.

这篇关于在 Swift 中覆盖具有不同类型的超类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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