Ask questionsA `first` operator that returns the first non-nil transformed value

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"] { $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

Answer questions pyrtsa

That would be a useful addition!

The current alternative could be code golfed down to this though:

let value = ["Hello", "10"].lazy.compactMap(Int.init).first

Related questions

No questions were found.
Github User Rank List