参见英文答案 >
Using a Type Variable in a Generic 4个
实际上,我希望有一个返回Metatype的协议(例如:Type.Type),我可以将其传递给Class,然后在需要时,将一个对象强制转换为该MetaType.我要强制转换它的原因是它将在tableView dequeue函数中使用,我想要转换为我指定的Type I.
实际上,我希望有一个返回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.
所以,不幸的是你编码的方式(或者幸运的是:)).
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。