在Swift中返回一个序列3

时间:2017-06-18 20:52:20

标签: swift sequence

我有一个协议Points,其方法应该返回Point个实例的有序序列。

我可以返回一个数组,但是我可以返回更通用的内容,以便Points的实现不需要将数据复制到数组中吗?

我试着这样做:

protocol Points {
  var points: Sequence {get}
}

但是得到错误:

  

协议'序列'只能用作通用约束,因为它具有自我或相关的类型要求

在较早的问题中,我读到了SequenceOf,但这似乎并不存在于Swift 3中。

以下是Points协议的示例实现:

extension PointSetNode: Points {
  var points: ?????? {
    return children.map{$0.points}.joined()
  }
}

...这里,children是一个数组。

1 个答案:

答案 0 :(得分:2)

作为Hamish mentions,您应该使用AnySequence。协议定义将是:

protocol Points {
  var points: AnySequence<Point> {get}
}

这方面的实现可能是:

var points: AnySequence<Point> {
  return AnySequence(children.map{$0.points}.joined())
}
相关问题