在Swift中存储然后转换为Metatypes

chi*_*lok 6 generics casting protocols swift metatype

实际上,我希望有一个返回元类型的协议(例如:Type.Type),我可以传递给一个Class,然后当我需要时,将一个对象转换为该MetaType.我要强制转换它的原因是它将在tableView dequeue函数中使用,我想要转换为我指定的Type I.

考虑这个精简版(下面的完整版).

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
Run Code Online (Sandbox Code Playgroud)

我很困惑为什么这不是一个类型,因为我们可以去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)
Run Code Online (Sandbox Code Playgroud)

Playground执行失败:MyPlayground.playground:43:44:错误:如果让newType = anyObject为'typeType'不是一个类型?typeType {

pac*_*ion 7

Ahmm.非常好的问题.几天前我有同样的3小时疼痛.最后,我找到了这个答案,主要思想是:

Swift的静态类型意味着必须在编译时知道变量的类型.

所以,不幸的是你编码的方式(或者幸运的是:)).