[swift-users] Guarding against an empty sequence

Erica Sadun erica at ericasadun.com
Mon May 9 12:54:31 CDT 2016


I know this is completely not answering your question, but why wouldn't an empty sequence return true? There is no element in an empty sequence that does not satisfy the predicate.

As for guarding against an empty sequence, you can create a buffered sequence type with 1-lookahead. Off the top of my head, n o guarantees for correctness:

public struct BufferedSequence<Base : SequenceType>:GeneratorType, SequenceType {
    
    internal var _base: Base
    internal var _generator: Base.Generator
    public var bufferedElement: Base.Generator.Element?
    
    public init(_ base: Base) {
        _base = base
        _generator = base.generate()
        bufferedElement = _generator.next()
    }

    public mutating func next() -> Base.Generator.Element? {
        defer {
            if bufferedElement != nil {
                bufferedElement = _generator.next()
            }
        }
        return bufferedElement
    }
    
    public func isEmpty() -> Bool {
        return bufferedElement == nil
    }
}

-- E


> On May 8, 2016, at 8:16 PM, Adriano Ferreira via swift-users <swift-users at swift.org> wrote:
> 
> Hi everyone!
> 
> I’m working on the following method:
> 
> extension SequenceType {
> 
>     /// Check if `predicate` is true for all elements of `self`
>     ///
>     /// - Parameter predicate: The predicate called on each element of `self`
>     ///
>     /// - Returns: True iff every element in `self` satisfies `predicate`, false otherwise
> 
>     @warn_unused_result
>     func all(@noescape where predicate: Generator.Element throws -> Bool) rethrows -> Bool {
>         for element in self where try !predicate(element) {
>             return false
>         }
> 
>         return true
>     }
> }
> 
> However, when the sequence is empty the method returns true, which is not the desired behaviour.
> 
> let a = [Int]()
> let b = a.all(where: { $0 > 7 })
> XCTAssertFalse(b)   // This fails, cause there’s no guard against an empty sequence
> 
> Does anyone know how to guard against an empty sequence?
> 
> I’m using Xcode 7.3.1 and Swift 2.2.
> 
> Best,
> 
> — A
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160509/ff3ad856/attachment.html>


More information about the swift-users mailing list