[swift-users] Guarding against an empty sequence

Adriano Ferreira adriano.ferreira at me.com
Sun May 8 21:16:13 CDT 2016

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

    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.


— A
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160508/2fb6790d/attachment.html>

More information about the swift-users mailing list