Skip to content

Instantly share code, notes, and snippets.

@ppeelen
Last active Jun 9, 2021
Embed
What would you like to do?
Swift: Lazy filter with prefix. Check if occurrence of X happens more than Y times using filter
struct FooBar {
let state: Bool
func isTrue() -> Bool { state } // Called 1000 times
func isFalse() -> Bool { !state } // Called 92 times
}
let fooList = (0..<1000).compactMap { n in FooBar(state: Bool.random()) }
let start = CFAbsoluteTimeGetCurrent()
if fooList.filter({ $0.isTrue() }).count > 1 {
print("> 1")
} else {
print("<= 1")
}
let diff = CFAbsoluteTimeGetCurrent() - start
debugPrint("First one took: \(diff)") // 0.02408897876739502
let secondStart = CFAbsoluteTimeGetCurrent()
if fooList.lazy.filter({ $0.isFalse() }).prefix(20).count > 1 {
print("> 1")
} else {
print("<= 1")
}
let diff2 = CFAbsoluteTimeGetCurrent() - secondStart
debugPrint("Second one took: \(diff2)") // Took 0.0023419857025146484
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment