swift - 如何编写存储相同类型的生成器的通用 Swift 类

标签 swift generics

我正在尝试编写一个处理同类对象的类,并且我想使用相同类型的(否则是任意的)生成器来提供这些对象。

本质上是这样的:

class MyGenericClass<T> {
  var source : GeneratorType
  var itemsProcessed = [ T ]()

  init(source: GeneratorType) {
    self.source = source
  }

  func getValue() -> T? {
    let item = source.next()
    if let item = item {
      itemsProcessed.append(item)
    }
    return item
  }
}

你可以这样调用它:

let myThing = MyGenericClass([ 1, 2, 3].generate())
let first   = myThing.getValue()

这引发了:'GeneratorType' can only be used as a generic constraint because it has Self or associated type requirements.

尝试了一些事情(例如 GeneratorType<T> ),但我不知道如何正确地做到这一点。 如何告诉 GeneratorType T 是它的元素类型别名?

最佳答案

你必须使用生成器类型作为类型占位符G, 并将其元素类型称为 G.Element:

class MyGenericClass<G : GeneratorType> {
    var source : G
    var itemsProcessed : [ G.Element ] = []

    init(source: G) {
        self.source = source
    }

    func getValue() -> G.Element? {
        let item = source.next()
        if let item = item {
            itemsProcessed.append(item)
        }
        return item
    }
}

let myThing = MyGenericClass(source: [ 1, 2, 3].generate())
let first   = myThing.getValue()
println(first) // Optional(1)

可选地,为元素类型定义一个类型别名:

class MyGenericClass<G : GeneratorType> {

    typealias T = G.Element

    var source : G
    var itemsProcessed : [ T ] = []

    // ...
}

关于swift - 如何编写存储相同类型的生成器的通用 Swift 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30982102/

相关文章:

Java泛型

c# - 用于类型推断的通用身份函数

Java 通配符有界泛型

swift - 如何更改 NSButton 的位置?

ios - 通过每个应用程序的扩展创建单例实例?

ios - 在 Realm 中查询具有反向关系的对象的正确方法

ios - 什么时候设置更改 heightForRowAt UITableView 动画被打破

Swift:为什么不能在扩展中添加商店属性?内存中的存储属性和计算属性有什么不同

java - 为什么 void method1(T obj) 不允许泛型?

c# - 将字符串转换为可空类型(int、double 等...)