简体   繁体   English

Swift:符合协议的AnyClass变量

[英]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? 有没有办法将C.self存储为具有符合协议类型的变量? Below does not compile, but it's what I'm ideally trying to do: 下面没有编译,但这是我理想的尝试:

let a: AnyClass<P> = C.self;
a.f();

The type of the object you are trying to store with C.self is C.Type . 您尝试使用C.self存储的对象类型是C.Type

The Type C conforms to the protocol P 类型C符合协议P

If you want to store your object by ensuring it conforms to P , use P.Type as the type. 如果要通过确保对象符合P来存储对象,请使用P.Type作为类型。

Example: 例:

let myObject: P.Type = C.self;
myObject.f();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM