Skip to content

A first operator that returns the first non-nil transformed value #21

Closed
@Qata

Description

@Qata

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions