[swift-evolution] [Pitch] Add an all algorithm to Sequence

Soroush Khanlou soroushkhanlou at gmail.com
Fri Mar 31 11:43:08 CDT 2017


I really like this proposal. This is one of the first extensions I add to a new Swift project. I think if we’re going to add `all`, we should consider adding `none` as well. `none` can be used currently as `!contains`, but sometimes boolean logic like that can be hard to follow.

Soroush

> Hi,
> 
> A short proposal for you as part of the algorithms theme. Hopefully non-controversial, aside from the naming of the method and arguments, about which controversy abounds. Online copy here:https://github.com/airspeedswift/swift-evolution/blob/9a778e904c9be8a3692edd19bb757b23c54aacbe/proposals/0162-all-algorithm.md
> 
> 
> Add anallalgorithm toSequence
> Proposal:SE-NNNN(file:///Users/ben_cohen/Documents/swift-evolution/proposals/0162-all-algorithm.md)
> Authors:Ben Cohen(https://github.com/airspeedswift)
> Review Manager: TBD
> Status:Awaiting review
> 
> Introduction
> 
> It is common to want to confirm that every element of a sequence equals a value, or matches a certain criteria. Many implementations of this can be found in use on github. This proposal adds such a method toSequence.
> 
> Motivation
> 
> You can achieve this in Swift 3 withcontainsby negating both the criteria and the result:
> 
> // every element is 9!nums.contains{ $0!=9}// every element is odd!nums.contains{ !isOdd($0) }
> 
> but these are a readability nightmare. Additionally, developers may not make the leap to realizecontainscan be used this way, so may hand-roll their ownforloop, which could be buggy, or compose other inefficient alternatives:
> 
> // misses opportunity to bail earlynums.reduce(true) { $0.0&&$0.1==9}// the most straw-man travesty I could think of...Set(nums).count==1&&Set(nums).first ==9
> Proposed solution
> 
> Introduce two algorithms onSequencewhich test every element and returntrueif they match:
> 
> nums.all(equal:9) nums.all(match: isOdd)
> Detailed design
> 
> Add the following extensions toSequence:
> 
> extensionSequence{/// Returns a Boolean value indicating whether every element of the sequence/// satisfies the given predicate.funcall(match criteria:(Iterator.Element)throws->Bool)rethrows->Bool}extensionSequencewhereIterator.Element:Equatable{/// Returns a Boolean value indicating whether every element of the sequence/// equals the given element.funcall(equalelement: Iterator.Element)->Bool}
> Source compatibility
> 
> This change is purely additive so has no source compatibility consequences.
> 
> Effect on ABI stability
> 
> This change is purely additive so has no ABI stability consequences.
> 
> Effect on API resilience
> 
> This change is purely additive so has no API resilience consequences.
> 
> Alternatives considered
> Not adding it.
> 
> 
> 
> 


More information about the swift-evolution mailing list