纯Swift类符合协议与静态方法 - 上传问题 [英] Pure Swift class conforming to protocol with static method - issue with upcasting

查看:205
本文介绍了纯Swift类符合协议与静态方法 - 上传问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我们有一个Swift协议,其中一个 static 方法:

Given we have a Swift protocol with one static method:

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

以及符合协议的纯Swift类:

and a pure Swift class which conforms to the protocol:

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

稍后当通过操作类型可创建来尝试使用该协议时,例如:

Later on when one tries to make use of that protocol by operating on type Creatable e.g.:

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

编译器抱怨如下:

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

问题是:这是Swift限制还是我正在使用协议和静态/类方法错误的方式。

The question is: is this a Swift limitation or I'm using the protocols and static/class method in the wrong way.

Objective-C等价物如下:

Objective-C equivalent would be something like:

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


推荐答案

A 可创建引用指向 Foo 实例,而不是 Foo 键入自身。

A Creatable reference points to an instance of Foo, not to the Foo type itself.

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

To get the equivalent of the class-level protocol implementation, you need an instance of Creatable.Type:

let c: Creatable.Type = Foo.self

然而,当您尝试使用它时会出现错误:

However, you’ll get an error when you then try to use it:

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

所有这些都说明,为什么你不能只使用函数来满足你的需求而不是元类型?

All that said, is there a reason why you can’t just use functions to fulfill your requirement, instead of metatypes?

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

这篇关于纯Swift类符合协议与静态方法 - 上传问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆