假设我有这样的代码:
func work<S: Sequence>(sequence: S) {
// do stuff
}
怎样才能计算出sequence
中有多少元素
我选择的明显版本是相当低效的:
var count = 0
for element in sequence {
count += 1
}
一定有更好的办法,对吧?
发布于 2015-02-27 05:29:08
我不认为有更好的方法来处理符合SequenceType
的任意类型。关于序列,我们唯一知道的是它有一个返回GeneratorType
的generate()
方法,而这个方法又有一个next()
方法。next()
方法前进到序列的下一个元素并返回它,如果没有下一个元素,则返回nil
。
请注意,根本不需要next()
最终返回nil
:序列可以有“无限”元素。
因此,枚举序列是对其元素进行计数的唯一方法。但这并不需要终止。因此,答案也可能是:接受序列参数的函数不需要知道元素的总数。
对于符合CollectionType
的类型,可以使用countElements()
函数(在SWIFT1.2中重命名为count()
)。
还有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
但这并不一定返回确切的元素数量。
https://stackoverflow.com/questions/28752743
复制相似问题