【问题标题】:How to access static variables in methods using Swift's 'abstract class'-like protocol extensions如何使用 Swift 的类似“抽象类”的协议扩展访问方法中的静态变量
【发布时间】:2016-04-18 03:25:14
【问题描述】:

我一直在尝试使用此处建议的协议和扩展在 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 方法中使用静态变量 numSides。我知道如果我将它设为实例变量,代码就会运行,但这似乎不是正确的方法。最好的方法是什么?

【问题讨论】:

    标签: swift polymorphism abstract-class swift-extensions swift-protocols


    【解决方案1】:

    您应该将 numSide 用作静态变量而不是实例变量。 您不能调用 Shape.numSides 但您可以使用引用具体类的 Self 关键字。 试试这个:

    Self.numSides
    

    【讨论】:

    • 不是自我,而是自我。谢谢!
    • 是的,我的答案中的 Self 是大写的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 2016-01-27
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多