加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Swift中存储然后转换为Metatypes

发布时间:2020-12-14 04:44:14 所属栏目:百科 来源:网络整理
导读:参见英文答案 Using a Type Variable in a Generic????????????????????????????????????4个 实际上,我希望有一个返回Metatype的协议(例如:Type.Type),我可以将其传递给Class,然后在需要时,将一个对象强制转换为该MetaType.我要强制转换它的原因是它将在tab
参见英文答案 > Using a Type Variable in a Generic????????????????????????????????????4个
实际上,我希望有一个返回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

我很困惑为什么这不是一个类型,因为我们可以去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:错误:’typeType’不是类型
????????????如果让newType = anyObject为? typeType {

解决方法

Ahmm.非常好的问题.几天前我有同样的3小时疼痛.最后,我找到了 this answer,主要的想法是:

Swift’s static typing means the type of a variable must be known at
compile time.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读