【问题标题】:Storing and then casting to Metatypes in Swift [duplicate]在 Swift 中存储然后转换为元类型 [重复]
【发布时间】: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


    【解决方案1】:

    嗯。非常好的问题。几天前我也有同样的 3 小时疼痛。最后,我找到了this answer,主要思路是:

    Swift 的静态类型意味着变量的类型必须在 编译时间。

    所以,不幸的是(或幸运的是:))你编码的方式是不允许的。

    【讨论】:

    • Aw :'( 为什么幸运,你会说?
    • @cilk,好吧,我有另一个答案给你,伙计:)stackoverflow.com/a/1517670/2463616
    • 啊,是的,很公平。非常适合安全,直到我想变得不安全为止。您是否找到了替代解决方案?
    • 嗯,我会想办法的:)
    • 在我的用例中,我实际上不需要强制转换为 Type 本身。 Type 始终是一个子类,而我传递的信息将始终传递给 Type 的 super,所以我改为转换为 super。奇怪的是,我确实需要访问该类型的类方法,它确实允许我这样做。 cell = collectionView.dequeueReusableCellWithReuseIdentifier(type.reuseIdentifierId, forIndexPath: indexPath) as? SuperType Were type 是有问题的元类型!
    猜你喜欢
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多