小编bea*_*eal的帖子

带有Protocol.Type的Swift泛型

我在Swift中遇到泛型问题(3):

我从服务器获得不同类的不同数据,实现相同的协议,我需要将它们放入具有泛型的类(例如Array)中.

我不知道数据属于哪个类,所以我需要使用协议.所以我有以下结构:

我的协议:

protocol MyProtocol {
    // some protocol stuff
}
Run Code Online (Sandbox Code Playgroud)

一些实现协议的类

class MyProtocolImpl1: MyProtocol{
    // some class stuff
}

class MyProtocolImpl2: MyProtocol {
    // some class stuff
}
....
Run Code Online (Sandbox Code Playgroud)

通用类:

final class MyGenericsClass<T: MyProtocol> {
    // some class stuff
}
Run Code Online (Sandbox Code Playgroud)

现在我想以这种方式使用这个类:

func createClass<T>(model: T.Type) -> MyGenericClass<T> {
    let myClass = MyGenericClass<T>()
    return myClass
}

...
Run Code Online (Sandbox Code Playgroud)

编辑

func getClass() -> MyProtocol.Type {
     return MyProtocolImpl1.self
}

let impl1 = getClass()
let impl2 = MyProtocolImpl2.self

let createdClass = createClass(impl1) //not working …
Run Code Online (Sandbox Code Playgroud)

generics protocols swift

6
推荐指数
1
解决办法
3984
查看次数

标签 统计

generics ×1

protocols ×1

swift ×1