gpt4 book ai didi

swift - 如何覆盖 Swift 中的属性?

转载 作者:可可西里 更新时间:2023-11-01 00:18:17 25 4
gpt4 key购买 nike

我有这个类和一个来自 Swift 教程的子类。遗憾的是,本教程没有提及如何覆盖属性。我的第一次测试惨遭失败:

// 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())

那么在子类上设置属性的正确方法是什么?

最佳答案

在您的示例中,您不想覆盖您只想更改其值的属性。最好的方法是 init 方法:

init(name: String) {
super.init(name: name)
numberOfSides = 3
}

要覆盖属性,您应该对其 getter 或 setter 方法进行一些更改,例如:

override var numberOfSides  {
get {
return super.numberOfSides
}
set {
super.numberOfSides = newValue + 10
}
}

关于swift - 如何覆盖 Swift 中的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24930564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com