Search code examples
swiftprotocolsswift2protocol-extension

How to call static methods on a protocol if they are defined in a protocol extension?


protocol Car {
    static func foo() 
}

struct Truck : Car {

}

extension Car {
    static func foo() {
        print("bar")
    }
}

Car.foo() // Does not work  
// Error: Car does not have a member named foo

Truck.foo() // Works

Xcode autocompletes the Car.foo() correctly, so what i'm asking is if its a bug that it doesn't compile (says it does not have a member named foo()). Could you call static methods directly on the protocol if they are defined in a protocol extension?


Solution

  • Apple doc

    Protocols do not actually implement any functionality themselves. Nonetheless, any protocol you create will become a fully-fledged type for use in your code.

    Therefore, you cannot call static methods directly of protocol.