Is there a point to declaring a static function on a protocol? The client using the protocol has to call the function on a type conforming to the protocol anyway right? That breaks the idea of not having to know the type conforming to the protocol IMO. Is there a way to call the static function on the protocol in a way where I don't have to know the actual type conforming to my protocol?
Calling Static FunctionIt is invoked by using the class name. For example: Math. sqrt(a); //calling the square root function of the Math class.
A static method provides NO reference to an instance of its class (it is a class method) hence, no, you cannot call a non-static method inside a static one.
Access to static functions is restricted to the file except where they are declared. When we want to restrict access to functions from outer world, we have to make them static. If you want access functions from other file, then go for global function i.e non static functions.
Nice question. Here is my humble point of view:
Pretty much the same as having instance methods declared in a protocol.
Yes, exactly like instance functions.
Nope. Look at the following code:
protocol Feline { var name: String { get } static func createRandomFeline() -> Feline init() } extension Feline { static func createRandomFeline() -> Feline { return arc4random_uniform(2) > 0 ? Tiger() : Leopard() } } class Tiger: Feline { let name = "Tiger" required init() {} } class Leopard: Feline { let name = "Leopard" required init() {} } let feline: Feline = arc4random_uniform(2) > 0 ? Tiger() : Leopard() let anotherFeline = feline.dynamicType.createRandomFeline()
I don't know the real type inside the variable feline
. I just know that it does conform to Feline
. However I am invoking a static protocol method.
I see, you would like to call a static method/function declared in a protocol without creating a value that conforms to the protocol.
Something like this:
Feline.createRandomFeline() // DANGER: compiler is not happy now
Honestly I don't know the reason why this is not possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With