我一直在尝试使用此处建议的协议和扩展在Swift中创建类似抽象的超类行为:Abstract classes in Swift Language 但我无法弄清楚如何编写使用静态(类)变量的方法。例如,如果我想获得抽象形状类的边界:
protocol Shape {
static var numSides: Int {get}
var sideLength: Double {get}
}
class Triangle: Shape {
static var numSides: Int = 3
var sideLength: Double
init (sideLength: Double) { self.sideLength = sideLength }
}
class Square: Shape {
static var numSides: Int = 4
var sideLength: Double
init (sideLength: Double) { self.sideLength = sideLength }
}
extension Shape {
func calcPerimeter() -> Double {
return sideLength * Double(numSides)
}
}
Swift并不希望我在calcPerimeter方法中使用静态var numSides。我知道如果我把它变成一个实例变量,那么代码就会运行,但这似乎不是正确的方法。这样做的最佳方式是什么?
答案 0 :(得分:2)
您应该使用numSide作为静态变量而不是实例1。
您不能调用Shape.numSides,但可以使用引用具体类的Self
关键字。
试试这个:
Self.numSides