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

6.2k Views Asked by At
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?

2

There are 2 best solutions below

1
On BEST ANSWER

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.

5
On

No, the error message isn't good, but it's telling you the correct thing.

Think of it this way, you can't have

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

This compiles with the error "Protocol methods may not have bodies".

Protocol extensions don't add abilities to protocols which don't exist.