Amit
Amit

Reputation: 645

What is iterator.element in swift?

I am just following iterator pattern, could you tell me what is S.Iterator.Element in below code & what is mean of Int where Turn == S.Iterator.Element ?

 func computeScoreIncrement<S : Sequence>(_ pastTurnsReversed: S) -> Int where Turn == S.Iterator.Element {
    var scoreIncrement: Int?
    for turn in pastTurnsReversed {
      if scoreIncrement == nil {
        scoreIncrement = turn.matched! ? 1 : -1
        break
      }
    }
//Turn is class name & nextScorer is protocol instance.
    return (scoreIncrement ?? 0) + (nextScorer?.computeScoreIncrement(pastTurnsReversed) ?? 0)
  }

Upvotes: 0

Views: 997

Answers (1)

Sweeper
Sweeper

Reputation: 271775

Iterator.Element is the easiest to understand here. The generic parameter S must be a type that conforms to Sequence, as you've specified here:

func computeScoreIncrement<S : Sequence>(_ pastTurnsReversed: S) -> Int
//                        ^^^^^^^^^^^^^^

Therefore, S.Iterator.Element refers to the type of sequence that S is. If, say, S is inferred to be [Int], then S.Iterator.Element is Int - [Int] is a sequence of Int.

Now onto the where Turn == S.Iterator.Element part.

As mentioned above, S must be a type that conforms to Sequence, but that's not all of the constraints! S.Iterator.Element must also be the same type as Turn. You didn't show how Turn is defined. It may be a generic parameter of the enclosing class, a class, struct or enum.

Thus, I can pass a [Turn] to this method, to instances of some other type that is a sequence of Turns.

Upvotes: 5

Related Questions