Skip to content

Instantly share code, notes, and snippets.

@cprovatas
Last active October 12, 2019 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cprovatas/8bd00e2c2d3f67d1963dc987cdc0aba7 to your computer and use it in GitHub Desktop.
Save cprovatas/8bd00e2c2d3f67d1963dc987cdc0aba7 to your computer and use it in GitHub Desktop.
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