Skip to content

Commit

Permalink
feat: add the first(where:) function to the Optional type
Browse files Browse the repository at this point in the history
  • Loading branch information
EmilioOjeda committed Aug 11, 2023
1 parent 6ce8995 commit 0917c89
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Sources/SwiftExtended/Optional.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
14 changes: 14 additions & 0 deletions Tests/SwiftExtendedTests/OptionalTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
)
}
}

0 comments on commit 0917c89

Please sign in to comment.