在swift中覆盖属性 [英] Overriding properties in swift
问题描述
例如a有第一个类
public class MyBaseButton: UIButton {
public var weight: Double = 1.0
public var text: String? {
get {
return self.titleForState(.Normal)
}
set {
return self.setTitle(newValue, forState: .Normal)
}
}
}
继承类:
public class SomeButton: SomeBaseButton {
override public var text: String? = "text"
override public var weight: Double = 2.0
}
所以,逻辑是 SomeClass
定义自己的文本和权重。
但是我收到错误:
So, the logic is that SomeClass
define own text and weight.
But I'm getting an errors:
对于文字:无法覆盖存储的属性'text'
对于重量:无法覆盖存储的属性'权重'
推荐答案
有趣的是,这在纯Swift类中效果很好。例如,这可以按预期工作:
Interestingly this works just fine in pure Swift classes. For example, this works as expected:
public class FooButton {
public var weight: Double = 1.0
}
public class BarButton: FooButton {
override public var weight: Double = 2.0
}
它不适合你的原因是因为你正在使用Objective-C类:因为 UIButton
是一个目标 - C类,它的所有子类也都是。因此,规则似乎有点不同。
The reason it does not work for you is because you are working with Objective-C classes: since UIButton
is an Objective-C class, all its subclasses will be too. Because of that, the rules seem to be a bit different.
Xcode 6.3实际上提供了更多信息。它显示以下两个错误:
Xcode 6.3 is actually a bit more informative. It shows the following two errors:
getter forweight覆盖Objective-C方法weight来自超类FooButton
权重的设定者覆盖Objective-C方法setWeight:来自超类Foobutton
Getter for "weight" overrides Objective-C method "weight" from superclass "FooButton" Setter for "weight" overrides Objective-C method "setWeight:" from superclass "Foobutton"
由于以下方法有效... 。
Since the following does work ...
public class BarButton: FooButton {
override public var weight: Double {
get {
return 2.0
}
set {
// Do Nothing
}
}
}
...我的猜测是这些方法根本没有正确合成。
... my guess is that these methods are simply not synthesized correctly.
我想知道是否这是编译器错误。或者是一个缺点。因为我认为可以处理这个案子。
I wonder if this is a compiler bug. Or a shortcoming. Because I think it could handle the case.
也许Swift设计师认为如果重写权重
您也可以在初始化程序中将其设置为不同的值。嗯。
Maybe the Swift designers thought that in case of overriding weight
you could also simply set it to a different value in your initializer. Hm.
这篇关于在swift中覆盖属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!