【发布时间】:2016-04-23 02:32:58
【问题描述】:
实际上,我希望有一个协议可以返回一个元类型(例如:Type.Type),我可以将它传递给一个类,然后当我需要时,将一个对象转换为那个元类型。我要转换它的原因是它将在 tableView dequeue 函数中使用,并且我想转换为我分配的类型。
考虑一下这个精简版(下面是完整版)。
let anyObject: AnyObject = anything()
let aType = type.type() // aType here is A.Type
if let newType = anyObject as? aType {
print(newType)
}
// error: 'aType' is not a type
我很困惑为什么这不是一个类型,因为我们可以去 aType.init() 来初始化它?
完整的示例代码如下(可以在 Playground 中运行)。
import UIKit
protocol P {
func type() -> A.Type
}
class A {
}
class B: A {
}
class C: A {
}
struct BData: P {
func type() -> A.Type {
return B.self
}
}
struct Foo {
let type: P
init(p: P) {
self.type = p
}
func create() {
let anyObject: AnyObject = anything()
let typeType = type.type()
if let newType = anyObject as? typeType {
print(newType)
}
}
func anything() -> AnyObject {
return B()
}
}
let data = BData()
let foo = Foo(p: data)
Playground 执行失败:MyPlayground.playground:43:44: error: 'typeType' 不是类型 如果让 newType = anyObject 为?类型类型 {
【问题讨论】:
标签: swift generics casting protocols metatype