Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// let base = [1,2,4,6,5,8,6]
// let filtered = base.takeUntil{ $0.isMultiple(of: 2) } // [2,4,6]
//
// let base = [2,4,6,5,8,6]
// let filtered = base.takeUntil{ $0.isMultiple(of: 2) } // [2,4,6]
//
// It stops collecting when the predicate fails (5,8,6 are not evaluated)
//
// Idea by https://twitter.com/K0nserv
//
extension Collection where Element: Equatable {
func takeUntil(predicate: (Element) -> Bool) -> some Collection {
self.drop { predicate($0) == false }.prefix(while: predicate)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment