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

Generics 如何在swift中编写通用工厂方法?,generics,swift,factory,type-inference,Generics,Swift,Factory,Type Inference,如果可能的话,我不知道如何编写一个方法来调用它的泛型类型的构造函数,该构造函数继承自常见的已知基类,以创建一些T的实例,而无需使用显式工厂函数,即使用类型推断提供的所有提示 在操场上工作的示例: // Let there be classes MyPod and Boomstick with common Base (not important) class Base : Printable { let value : String; init(_ value : String) { s

如果可能的话,我不知道如何编写一个方法来调用它的泛型类型的构造函数,该构造函数继承自常见的已知基类,以创建一些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 of Boomstick(n) instead of Base(n) in here
func createSome<T : Base>() -> T[] {
    var result = Array<T>()
    for n in 1...5 {
        result += T(toString(n))
    }
    return result
}
// This seems to be fine. 
// I was expecting call of createSome<Boomstick>() { ... result += Boomstick(n) ...
let objs : Boomstick[] = createSome() 
// Prints: Base.1, Base.2, ... not much wished Boomstick.1, Boomstick.2, ...
println(objs)
let objs : [Boomstick] = createSome()
objs[0]
//让MyPod和Boomstick类具有公共基(不重要)
类基:可打印{
let value:String;init(value:String){self.value=“Base.+value}
变量说明:字符串{返回值}
}
MyPod类:基本类{
init(value:String){super.init(“MyPod.+value)}
}
类别:基本{
init(value:String){super.init(“Boomstick.+value)}
}
//问题:不知道如何在这里强制调用动臂杆(n)而不是底部(n)
func createSome()->T[]{
var result=Array()
对于1…5中的n{
结果+=T(toString(n))
}
返回结果
}
//这似乎很好。
//我希望调用createSome(){…result+=Boomstick(n)。。。
让objs:Boomstick[]=createSome()
//打印:Base.1,Base.2,…不太希望使用Boomstick.1,Boomstick.2。。。
println(objs)
一个显而易见的解决方案是将创建委托给调用方,但这似乎很笨拙:

func createSome<T>(factory : (Int)->T) { ... }
func-createSome(工厂:(Int)->T){…}
多谢各位


PS:createSome()->Base[]赋值给objs:Boomstick[]不是类型安全违规吗?

现在我还不知道为什么,但用初始值设定项定义协议似乎只起作用:

protocol A {
    init(_ value: String)
}
您可以在所有类中实现此协议,如下所示

class Base : Printable, A {
    let value : String;
    init(_ value : String) { self.value = "Base." + value }
    var description: String { return value }
}

class MyPod : Base, A {
    init(_ value: String) { super.init("MyPod." + value) }
}

class Boomstick : Base, A {
    init(_ value: String) { super.init("Boomstick." + value) }
}
createSome()函数中使用
A
而不是
Base

func createSome<T : A>() -> [T] {
    var result = Array<T>()
    for n in 1...5 {
        result += T(toString(n))
    }
    return result
}
它会打印:

{value "Base.Boomstick.1"}
还尝试使用
MyPod
Base
并打印预期结果。
测试它,让我知道它是否对你也有效。

可能的重复已经不起作用了。看,这实际上相当好。它甚至可以用于优势:将基类升级为协议=>更少的继承,更多的表达看起来像什么…谢谢你!…该死的(第二篇文章):-D