Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: AnyClass variable that conforms to protocol

I have a static function I want to call on a class conforming to a protocol.

protocol P {
    static func f();
}

class C: P {
    static func f() {}
}

Is there a way to store C.self as a variable with a type that conforms to the protocol? Below does not compile, but it's what I'm ideally trying to do:

let a: AnyClass<P> = C.self;
a.f();
like image 263
kev Avatar asked Mar 14 '16 21:03

kev


1 Answers

The type of the object you are trying to store with C.self is C.Type.

The Type C conforms to the protocol P

If you want to store your object by ensuring it conforms to P, use P.Type as the type.

Example:

let myObject: P.Type = C.self;
myObject.f();
like image 173
Adam Zielinski Avatar answered Sep 24 '22 06:09

Adam Zielinski