如何获得符合"序列"的类型的计数?

Mar*_*sel 7 count sequence swift

假设我有这段代码:

func work<S: Sequence>(sequence: S) {
    // do stuff
}
Run Code Online (Sandbox Code Playgroud)

我怎么能弄清楚有多少元素sequence
我想要的明显版本是非常低效的:

var count = 0
for element in sequence {
    count += 1
}
Run Code Online (Sandbox Code Playgroud)

必须有一个更好的方式,对吧?

Mar*_*n R 7

我认为没有一种更好的方法可以满足任意类型 SequenceType.关于序列唯一知道的是有一个generate()返回a 的方法GeneratorType,该next()方法又有一个方法.该next()方法前进到序列的下一个元素并返回它,或者nil如果没有下一个元素则返回.

请注意,next()最终不需要返回 nil:序列可能具有"无限"元素.

因此,枚举序列是计算其元素的唯一方法.但这不需要终止.因此答案也可能是:采用序列参数的函数不需要知道元素的总数.

对于符合CollectionType您的类型,可以使用该 countElements()函数(count()在Swift 1.2中重命名).

还有underestimateCount():

/// Return an underestimate of the number of elements in the given
/// sequence, without consuming the sequence.  For Sequences that are
/// actually Collections, this will return countElements(x)
func underestimateCount<T : SequenceType>(x: T) -> Int
Run Code Online (Sandbox Code Playgroud)

但这并不一定会返回确切的元素数量.

  • @MarcusRossel:好问题.似乎对于大多数(所有?)具体集合,Index.Distance实际上是一个Int,所以你可以将你的函数声明为`func myfunc <C:CollectionType where C.Index.Distance == Int>(coll:C)` .或者你只需​​要一个数组作为参数.否则我的想法已经不多了,晚上已经太晚了.也许你只是问另一个问题:) (2认同)