[swift-evolution] Proposal: Add SequenceType.first

Susan Cheng susan.doggie at gmail.com
Thu Dec 31 06:20:03 CST 2015

Generator should always generates value from start of sequence. I don't see
any problems with this implementation.

Dave Abrahams via swift-evolution <swift-evolution at swift.org> 於
2015年12月31日星期四 寫道:

> On Dec 30, 2015, at 3:57 PM, Kevin Ballard via swift-evolution <
> swift-evolution at swift.org
> <javascript:_e(%7B%7D,'cvml','swift-evolution at swift.org');>> wrote:
> It's sometimes useful to get the first element of a sequence. To that end
> I'd like to propose
> extension SequenceType {
>     /// Returns the first element of `self`, or `nil` if `self` is empty.
>     /// - Complexity: O(1)
>     var first: Self.Generator.Element? {
>         var gen = generate()
>         return gen.next()
>     }
> }
> I think it makes sense to add this property to the definition of
> SequenceType as well, so various sequences can override it to avoid
> constructing a generator.
> With this added to SequenceType, we can remove it from CollectionType, as
> the behavior will be the same.
> Property accesses should not mutate the receiver, and because of how
> Sequences work, inspecting first may consume the first element. I suggest
> you consider adding a BufferedSequence<Base: SequenceType> that has a
> stable first property (at least until it is iterated)
> Another related adapter I’d like to add is a model of CollectionType that
> is backed by a sequence and lazily populated in fixed-sized chunks.
> -Dave
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151231/5e89bda8/attachment.html>

More information about the swift-evolution mailing list