Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a static function on a protocol in a generic way?

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?

like image 535
SirRupertIII Avatar asked May 13 '16 21:05

SirRupertIII


People also ask

How do you call a static function?

Calling Static FunctionIt is invoked by using the class name. For example: Math. sqrt(a); //calling the square root function of the Math class.

Can I call a static method inside a regular method?

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.

How do you call a static method from another file?

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.


1 Answers

Nice question. Here is my humble point of view:

Is there a point to declaring a static function on a protocol?

Pretty much the same as having instance methods declared in a protocol.

The client using the protocol has to call the function on a type conforming to the protocol anyway right?

Yes, exactly like instance functions.

That breaks the idea of not having to know the type conforming to the protocol IMO.

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.

Is there a better way to do this?

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.

like image 54
Luca Angeletti Avatar answered Oct 04 '22 20:10

Luca Angeletti