Swift属性覆盖不起作用 [英] Swift property override not working
问题描述
当我尝试覆盖属性时,我收到错误无法覆盖具有只读属性的可变属性
When I try to override a property I get an error "can not override mutable property with read-only property"
我提供了get和set in super class。
I have provided get and set in the super class.
class Card {
var contents:String {
get {
return self.contents
}
set {
self.contents = newValue
}
}
init() {
self.contents = ""
}
}
这是我的子类,我试图覆盖content属性。
Here is my Subclass where I am trying to override the "contents" property.
class PlayingCard: Card {
override var contents:String { //<-- this is where I get the build error
get {
var rankStrings:Array<String> = PlayingCard.rankStrings()
return rankStrings[Int(self.rank)] + self.suit
}
}
}
我究竟做错了什么?
推荐答案
如果您要覆盖的属性同时具有getter和setter,则还需要在子类中同时提供这两个属性。这是相关部分来自Swift语言指南(强调我的):
If the property you're overriding has both a getter and a setter, you need to provide both in your subclass as well. Here's the relevant part from the Swift language guide (emphasis mine):
您可以将继承的只读属性呈现为读写通过在子类
属性覆盖中提供getter和setter来
属性。 但是,您不能将继承的
读写属性作为只读属性。
如果你没有对该值做任何特殊处理,那么你通常希望将设置的值传递给基类:
If you're not doing anything special with the value, then you'll typically want to pass the value being set on to the base class:
set {
super.contents = newValue
}
你也可以用一个空的setter来丢弃这个值(尽管我不能想到一个很好的理由去做这个):
You could also just discard the value with an empty setter (although I can't think of a good reason to do this offhand):
set { }
我也想要指出您的卡
类中的内容
属性中存在无限循环。当你这样做时:
I also wanted to point out that you have an infinite loop in the contents
property in your Card
class. When you you do this:
get {
return self.contents
}
你实际上只是再次调用相同的getter,创建一个无限循环;你对二传手做同样的事情。 Swift不像Objective-C那样自动为您的属性创建ivars,因此您需要自己创建它们。创建该属性的更合适的方法是执行以下操作:
You're actually just calling that same getter again, creating an infinite loop; you're doing the same with the setter. Swift doesn't create ivars for your properties automatically like Objective-C did, so you need to create them yourself. A more appropriate way to create that property would be to do something like this:
class Card {
private var _contents: String
var contents: String {
get {
return _contents
}
set {
_contents = newValue
}
}
init() {
_contents = ""
}
}
但是,由于除了在setter和getter中设置并返回 _contents
之外没有做任何其他事情,你可以将其简化为:
However, since you're not doing anything other than setting and returning _contents
in your setter and getter, you can simplify it down to this:
class Card {
var contents: String = ""
init() {
}
}
注意: contents
也可能是使用可选( String?
)并将其设置为的理想选择nil
而不是将其初始化为空字符串。
Note: contents
might also be a good candidate for using an optional (String?
) and setting it to nil
rather than initializing it to an empty string.
这篇关于Swift属性覆盖不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!