如何为SequenceType实现泛型求和函数,其中Generator.Element的类型为Int

Pal*_*ndo 3 generics swift

我正在尝试编写一个函数,用于对各种SequenceType实现的迭代性能进行基准测试.它应该简单地对序列的内容求和,其中所有元素都是Ints.我正在努力表达对函数的通用约束......

func sum<S: SequenceType where S.Generator.Element: Int>(s: S) -> Int {
  var sum = 0
  for i in s {
      sum += i
  }
  return sum
}
Run Code Online (Sandbox Code Playgroud)

这导致以下两个错误:

  • 类型‘S.Generator.Element’约束为非协议类型’Int’
  • 二进制运算符'+=‘不能应用于类型’Int'和的操作数’S.Generator.Element’

有没有办法定义此函数来处理任何SequenceType实现,具有专门的元素Int

Mar*_*n R 5

约束应该是S.Generator.Element == Int:

func sum<S: SequenceType where S.Generator.Element == Int>(s: S) -> Int {
    var sum = 0
    for i in s {
        sum += i
    }
    return sum
}
Run Code Online (Sandbox Code Playgroud)

整数类型略微更通用:

func sum<S: SequenceType, T : IntegerType where S.Generator.Element == T >(s: S) -> T {
    var sum : T = 0
    for i in s {
        sum += i
    }
    return sum
}
Run Code Online (Sandbox Code Playgroud)