Benjohn
Benjohn

Reputation: 13887

Returning a Sequence in Swift 3

I have a protocol Points with a method that should return an ordered sequence of Point instances.

I could return an array, but can I return something more generic so that implementations of Points needn't copy data in to an array?

I tried to do this:

protocol Points {
  var points: Sequence {get}
}

But get the error:

Protocol 'Sequence' can only be used as a generic constraint because it has Self or associated type requirements

In older questions I read about SequenceOf, but this doesn't seem to exist in Swift 3.

Here's an example implementation of the Points protocol:

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

… here, children is an array.

Upvotes: 4

Views: 737

Answers (1)

Benjohn
Benjohn

Reputation: 13887

As Hamish mentions you should use AnySequence for this. The protocol definition will be:

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

An implementation of this might be:

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

Upvotes: 2

Related Questions