纯Swift类符合协议与静态方法 – 问题与上传

鉴于我们有一个static方法的Swift协议:

 protocol Creatable: class { static func create() -> AnyObject } 

和一个符合协议的纯Swift类:

 class Foo : Creatable { static func create() -> AnyObject { return Foo() as AnyObject } } 

稍后,当尝试通过操作typesCreatable来使用该协议时,例如:

 var f : Creatable = Foo.self f.create() 

编译器抱怨如下:

 error: type 'Foo.Type' does not conform to protocol 'Creatable' 

问题是:这是一个Swift的限制,或者我用错误的方式使用协议和静态/类方法。

Objective-C的等价物会是这样的:

 Class someClass = [Foo class]; if ([someClass conformsToProtocol:@protocol(Creatable)]) { [(Class <Foo>)someClass create]; } 

Creatable引用指向Foo一个实例 ,而不是Footypes本身。

要获得类级协议实现的等价物,您需要一个Creatable.Type的实例:

 let c: Creatable.Type = Foo.self 

但是,如果您尝试使用它,则会出现错误:

 // error: accessing members of protocol type value 'Creatable.Type' is unimplemented c.create() 

所有这一切,是否有一个原因,你不能只是使用函数来满足您的要求,而不是metatypes?

 let f = Foo.create // f is now a function, ()->AnyObject, that creates Foos let someFoo = f() 

使用.Type是关键:

 var f : Creatable.Type = Foo.self 

这不再给出“未实现”的错误。 请参阅以下完整代码:

 protocol Creatable: class { static func create() -> AnyObject } class Foo : Creatable { static func create() -> AnyObject { return Foo() as AnyObject } } var f : Creatable.Type = Foo.self f.create()