[swift-users] Guarding against an empty sequence

Jeremy Pereira jeremy.j.pereira at googlemail.com
Tue May 10 08:49:07 CDT 2016


I would agree with everybody else who says an empty sequence should return true (and your documentation comment seems to confirm that). However, to implement the behaviour you want, there is no need to think of something clever, simply count the number of iterations of the for loop.

    func all(@noescape where predicate: Generator.Element throws -> Bool) rethrows -> Bool {
	var count = 0
        for element in self {
	    guard try predicate(element) else { return false }
	    count += 1
        }
        return count > 0
    }

YMMV, but I think the above (even without the count) is more readable than the original version with the where clause because it is more explicit about how the algorithm works.

Obviously “count” could be a boolean that starts out false and gets set to true on each iteration after the guard and I know you don’t like the idea, but it is cleaner and simpler than mucking about with explicitly calling next() or creating a whole new buffered sequence just to avoid two lines of code.

> On 9 May 2016, at 03:16, 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



More information about the swift-users mailing list