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)
必须有一个更好的方式,对吧?
我认为没有一种更好的方法可以满足任意类型
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)
但这并不一定会返回确切的元素数量.