Search code examples
swiftpolymorphismabstract-classswift-extensionsswift-protocols

How to access static variables in methods using Swift's 'abstract class'-like protocol extensions


I've been trying to make abstract superclass-like behaviour in Swift using the protocols and extensions suggested here: Abstract classes in Swift Language But I can't figure out how to write methods that make use of static (class) variables. For example, if I want to get the perimeter of an abstract shape class:

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 doesn't want me to use static var numSides in the calcPerimeter method. I know that if I made it an instance variable the code would run, but this doesn't seem like the right way to go. What is the best way to do this?


Solution

  • You should use numSide as a static variable not instance one. You cannot call Shape.numSides but you can use Self keyword which reference to the concrete class. Try this:

    Self.numSides