我有Swift教程中的这个Class和一个子类。遗憾的是,教程没有提到如何覆盖属性。我的第一次测试失败了:
// generic shape
class Shape {
var numberOfSides = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return self.name + " with \(numberOfSides) sides."
}
}
// creating a subclass and reset the property
class Triangle: Shape {
// this doesnt work
override var numberOfSides = 3
// this also doesnt work
var numberOfSides = 3
// and this doesnt work either
numberOfSides = 3
// this works
override func simpleDescription() -> String {
return "Triangle name: " + self.name + " number of sides: \(numberOfSides)"
}
}
var blurgh = Triangle(name: "supertriangle")
println(blurgh.simpleDescription())
那么在子类上设置属性的正确方法是什么?
答案 0 :(得分:3)
在您的示例中,您不希望覆盖您只想更改其值的属性。 最好的方法是使用init方法:
init(name: String) {
super.init(name: name)
numberOfSides = 3
}
要覆盖属性,您应该对getter或setter方法进行一些更改,例如:
override var numberOfSides {
get {
return super.numberOfSides
}
set {
super.numberOfSides = newValue + 10
}
}
答案 1 :(得分:2)
init方法怎么样?
...
func init() {
super.init()
self.numberOfSides = 3
}
答案 2 :(得分:2)
我想扩展 Greg 的回答。与get
和set
一起,有willSet
和didSet
个选项。将下一个代码复制到游乐场并使用它来查看如何使用它
import UIKit
class TestClass {
var testValue: String = ""
var anotherProperty: String = ""
}
class AnotherTestClass: TestClass {
override var testValue: String {
didSet {
if countElements(super.testValue) > 2 {
super.testValue = "222"
}
}
willSet {
if countElements(newValue) > 2 {
super.anotherProperty = "33"
}
}
}
}
var c: AnotherTestClass = AnotherTestClass()
c.testValue = "123"