加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:40:55 所属栏目:百科 来源:网络整理
导读:我不知道如果有可能,如何编写调用它的泛型类型的构造函数的方法继承自公知的基类 T:基础创建T的一些实例而不诉诸显式工厂函数,即通过类型推断提供所有铃声和口哨声. 在游乐场中工作的示例: // Let there be classes MyPod and Boomstick with common Base
我不知道如果有可能,如何编写调用它的泛型类型的构造函数的方法继承自公知的基类< 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,它打印出预期的结果.测试一下,让我知道它是否也适合你.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读