如何获取符合`Sequence`的类型的计数? [英] How to get the count of a type conforming to `Sequence`?
问题描述
假设我有以下代码:
func work<S: Sequence>(sequence: S) {
// do stuff
}
我怎么知道其中有多少个元素序列
?
我想要的明显版本效率很低:
How could I figure out how many elements there are in sequence
?
The obvious version I'd go for is pretty inefficient:
var count = 0
for element in sequence {
count += 1
}
肯定有更好的方法吧?
推荐答案
我不认为对于符合
SequenceType
的任意类型,有更好的方法。关于序列的唯一已知信息是
具有 generate()
方法,该方法返回 GeneratorType
,而
具有 next()
方法。 next()
方法前进到序列的下一个
元素并返回它,或者返回 nil
如果没有
没有下一个元素。
I do not think that there is a better method for an arbitrary type conforming to
SequenceType
. The only thing that is known about a sequence is that
is has a generate()
method returning a GeneratorType
, which in turn
has a next()
method. The next()
method advances to the next
element of the sequence and returns it, or returns nil
if there
is no next element.
请注意, next()
最终返回
nil
:一个序列可能包含无限元素。
Note that it is not required at all that next()
eventually returns
nil
: a sequence may have "infinite" elements.
因此,请枚举该序列是计算其
元素的唯一方法。但这不必终止。因此答案
也可能是:带有序列参数的函数不必知道
元素的总数。
Therefore enumerating the sequence is the only method to count its elements. But this need not terminate. Therefore the answer could also be: A function taking a sequence argument should not need to know the total number of elements.
对于符合 CollectionType
的类型,可以使用
countElements()
函数(重命名为在Swift 1.2中是 count()
。
For types conforming to CollectionType
you can use the
countElements()
function (renamed to count()
in 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
但这不一定返回确切的元素数。
but that does not necessarily return the exact number of elements.
这篇关于如何获取符合`Sequence`的类型的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!