Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift Sequence Helpers
// These helpers allow for basic operations to be performed while still iterating over a sequence once without
// adding all of the common boilerplate code you'd normally have to write
extension Sequence {
// filter + forEach
func forEach(where predicate: (Element) -> Bool, _ body: (Element) throws -> Void) rethrows {
for element in self where predicate(element) {
try body(element)
}
}
// compactMap + forEach
func forEach<TransformedElement>(compactMapping: (Element) -> TransformedElement?, _ body: (TransformedElement) throws -> Void) rethrows {
for element in self {
guard let transformed = compactMapping(element) else { continue }
try body(transformed)
}
}
}
// Usage (Playground Context):
// Example 1: Use function that takes in argument
func doStuff(_ element: Foo) { /* ... */ }
elements.forEach(where: { $0 < 3 }, doStuff(_:))
// Example 2: Use block as a trailing closure
elements.forEach(where: { $0 < 3 }) {
doStuff($0)
}
// Example 3: Use function that takes in argument
elements.forEach(compactMapping: { $0 as? Foo }, doStuff(_:))
// Example 4: Use block as trailing closure
elements.forEach(compactMapping: { $0 as? Foo }) {
doStuff($0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment