From 0917c89b0488cea303002052c550b5f284dc5f71 Mon Sep 17 00:00:00 2001 From: Emilio Ojeda Date: Fri, 11 Aug 2023 12:06:33 -0600 Subject: [PATCH] feat: add the `first(where:)` function to the `Optional` type --- Sources/SwiftExtended/Optional.swift | 11 +++++++++++ Tests/SwiftExtendedTests/OptionalTests.swift | 14 ++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/Sources/SwiftExtended/Optional.swift b/Sources/SwiftExtended/Optional.swift index c5a1f95..7caa8c3 100644 --- a/Sources/SwiftExtended/Optional.swift +++ b/Sources/SwiftExtended/Optional.swift @@ -143,4 +143,15 @@ public extension Optional where Wrapped: Collection, Wrapped.Element: Equatable return collection .contains(where: \.self == element) } + + /// Finds the first element of the wrapped `Collection` satisfying a `predicate`, if any. + /// - Parameter predicate: The predicate to satisfy. + /// - Returns: The first found element that satisfies the predicate. + func first(where predicate: (Wrapped.Element) -> Bool) -> Wrapped.Element? { + guard let collection = self else { + return nil + } + return collection + .first(where: predicate) + } } diff --git a/Tests/SwiftExtendedTests/OptionalTests.swift b/Tests/SwiftExtendedTests/OptionalTests.swift index 507fb43..72ab11c 100644 --- a/Tests/SwiftExtendedTests/OptionalTests.swift +++ b/Tests/SwiftExtendedTests/OptionalTests.swift @@ -172,4 +172,18 @@ final class OptionalTests: XCTestCase { XCTAssertNil(nilDueToLeftHandSide) XCTAssertNil(nilDueToRightHandSide) } + + func testFirstWhere() { + // given + let optionalABC: [String]? = ["A", "B", "C"] + + // then + XCTAssertNil(optionalABC.first(where: \.self == "D")) + XCTAssertNotNil(optionalABC.first(where: \.self == "A")) + XCTAssertNil( + Optional<[String]> + .none + .first(where: \.self == "A") + ) + } }