【发布时间】:2017-01-05 15:12:08
【问题描述】:
我在 Swift (3) 中遇到泛型问题:
我从服务器获得不同类的不同数据,实现相同的协议,我需要将它们放入具有泛型的类(例如数组)中。
我不知道数据是哪个类,所以我需要使用协议。所以我有以下结构:
我的协议:
protocol MyProtocol {
// some protocol stuff
}
一些实现协议的类
class MyProtocolImpl1: MyProtocol{
// some class stuff
}
class MyProtocolImpl2: MyProtocol {
// some class stuff
}
....
泛型类:
final class MyGenericsClass<T: MyProtocol> {
// some class stuff
}
现在我想这样使用这个类:
func createClass<T>(model: T.Type) -> MyGenericClass<T> {
let myClass = MyGenericClass<T>()
return myClass
}
...
编辑
func getClass() -> MyProtocol.Type {
return MyProtocolImpl1.self
}
let impl1 = getClass()
let impl2 = MyProtocolImpl2.self
let createdClass = createClass(impl1) //not working
let createdClass = createClass(impl2) //working
做createClass(impl1)我得到这个错误:
cannot invoke 'createClass' with an argument list of type '(MyProtocol.Type)'
将 MyProtocol 更改为一个类可以解决问题,但是我不能确定从它继承的每个类都实现了所需的方法。
有人知道如何解决这个问题吗?
【问题讨论】:
-
func createClass<T: MyProtocol>修复了吗? -
您能解决问题吗?
-
你想将
MyProtocol.self传递给函数,而不是MyProtocol.Type。但即便如此,您也不能拥有MyGenericClass<MyProtocol>,因为MyProtocol不是符合MyProtocol的类型——请参阅Protocol doesn't conform to itself? -
此链接中的解释非常有帮助。谢谢你。因此,如果 Swift 目前不支持此权利,是否有一些很好的解决方法来解决这个问题?你有什么想法吗?
-
@beal 真的取决于您使用
MyGenericClass的目的。问题的真正症结在于您试图混合通用占位符,这些占位符在编译时与您在运行时获得的类型一起解决。您很可能应该使用非泛型类并使用类型MyProtocol而不是泛型占位符T。现在您谈论的是符合MyProtocol的任何 类型,而不是一种特定类型——因为您不知道直到运行时该类型是什么。