Closed
Description
I found myself often having to find the first element in an array that passes an optional initialiser.
If I wanted to stick to a purely functional paradigm (which I do, I'm a zealot) I need to do some pretty not-ideal transforms to allow this behaviour without defining a new function.
let value = ["Hello", "10"].lazy.map(Int.init).first { $0 != nil }.flatMap { $0 }
This could be trivialised with the following (naive) implementation.
public extension Sequence {
/// Returns the first element in `self` that `transform` maps to a `.some`.
func first<Result>(of transform: (Element) throws -> Result?) rethrows -> Result? {
for value in self {
if let value = try transform(value) {
return value
}
}
return nil
}
}
Metadata
Metadata
Assignees
Labels
No labels