什么是swift中的iterator.element?

时间:2017-08-11 06:20:38

标签: swift iterator

我只是关注迭代器模式,你能告诉我下面代码中的S.Iterator.Element是什么吗?什么是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)
  }

1 个答案:

答案 0 :(得分:4)

Iterator.Element是最容易理解的。通用参数S必须是符合Sequence的类型,如您在此处指定的那样:

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

因此,S.Iterator.Element指的是S的序列类型。如果推断S[Int],则S.Iterator.ElementInt - [Int]Int的序列。

现在进入where Turn == S.Iterator.Element部分。

如上所述,S必须是符合Sequence的类型,但并非所有约束都是如此! S.Iterator.Element也必须是与Turn相同的相同类型。您没有说明如何定义Turn。它可以是封闭类的通用参数,类,结构或枚举。

因此,我可以将[Turn]传递给此方法,传递给Turn s序列的其他类型的实例。