gpt4 book ai didi

ios - 符合静态方法协议(protocol)的纯 Swift 类 - 向上转换问题

转载 作者:IT王子 更新时间:2023-10-29 05:23:41 24 4
gpt4 key购买 nike

假设我们有一个带有一个static方法的Swift协议(protocol):

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

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

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

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

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

编译器提示如下:

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

问题是:这是 Swift 的限制还是我以错误的方式使用了协议(protocol)和静态/类方法。

等效于 Objective-C 的内容如下:

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

最佳答案

Creatable 引用指向 Foo实例,而不是 Foo 类型本身。

要获得类级协议(protocol)实现的等效项,您需要 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()

关于ios - 符合静态方法协议(protocol)的纯 Swift 类 - 向上转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28973519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com