小编Ada*_*dam的帖子

如何在swift中编写通用工厂方法?

我不知道如果有可能,如何编写调用它的泛型类型的构造函数的方法继承自公共已知的基类<T:Base>来创建T的一些实例而不依赖于显式工厂函数,即所有的钟声和口哨由类型推断提供.

在游乐场中工作的示例:

// Let there be classes MyPod and Boomstick with common Base (not important)
class Base : Printable {
    let value : String; init(_ value : String) { self.value = "Base." + value }
    var description: String { return value }
}
class MyPod : Base {
    init(_ value: String) { super.init("MyPod." + value) }
}
class Boomstick : Base {
    init(_ value: String) { super.init("Boomstick." + value) }
}
// PROBLEM: do not know how to force call …
Run Code Online (Sandbox Code Playgroud)

generics factory type-inference swift

5
推荐指数
1
解决办法
4751
查看次数

标签 统计

factory ×1

generics ×1

swift ×1

type-inference ×1