Skip to content

Instantly share code, notes, and snippets.

@RuiAAPeres
Created January 27, 2021 16:09
Show Gist options
  • Save RuiAAPeres/926cc5c1949e0482e4a89705655aac77 to your computer and use it in GitHub Desktop.
Save RuiAAPeres/926cc5c1949e0482e4a89705655aac77 to your computer and use it in GitHub Desktop.
// 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