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

2

12
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?

Ola answered 14/8, 2015 at 8:48 Comment(4)
Car is not an object so you can't send it any messages.Crowd
This feels like a bug to me. Since the default implementation binds actual functionality directly to the protocol, it should be callable on the protocol itself.Revolutionary
@Revolutionary "the default implementation binds actual functionality directly to the protocol" is not a true statement. The default implementation binds functionality to class and structs which conform to the protocol. There are reasons protocols don't have implementations.Shovel
What seems like a bug is that Xcode actually suggest the autocomplete, if its not possible it should not do thatOla
L
9

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.

Langlauf answered 14/8, 2015 at 9:44 Comment(1)
They can do it with a simple hack. Here is my related answer. https://mcmap.net/q/401582/-how-can-i-call-a-static-function-on-a-protocol-in-a-generic-wayKrum
S
1

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.

Shovel answered 14/8, 2015 at 9:35 Comment(5)
In Swift 2 protocol extensions can actually add default implementations.Revolutionary
@Revolutionary Yes, they add default implementations to classes and structs… not protocols. A protocol has no implementation.Shovel
This says otherwise, or am I mistaken?Revolutionary
@Revolutionary Protocols can be extended to provide method and property implementations to conforming types. The new protocol extension adds to a class or struct conforming to the protocol, but the protocol is still just a protocol. Protocols don't have an implementation.Shovel
So the point is that the default implementation is added to each conforming class/struct instead of the protocol. I see your point. Still, this feels a bit weird to me.Revolutionary

© 2022 - 2024 — McMap. All rights reserved.