微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我不知道如果有可能,如何编写调用它的泛型类型的构造函数方法继承自公知的基类< T:基础>创建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)

一个明显的解决方案是将创建委托给调用者,但这似乎很笨重:

func createSome<T>(factory : (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
}

在操场上测试:

let objs : [Boomstick] = createSome()
objs[0]

它打印:

{value "Base.Boomstick.1"}

还尝试使用MyPod和Base,它打印出预期的结果.测试一下,让我知道它是否也适合你.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐