繁体   English   中英

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

[英]Pure Swift class conforming to protocol with static method - issue with upcasting

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

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

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

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

稍后当人们试图通过操作类型Creatable来使用该协议时,例如:

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实例 ,而不指向Foo类型本身。

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

let c: Creatable.Type = Foo.self

但是,当您尝试使用它时,您将收到错误:

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

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

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()

暂无
暂无

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

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