Skip to content

Commit

Permalink
feat: add the Scala-like contains functions to the Optional type
Browse files Browse the repository at this point in the history
  • Loading branch information
EmilioOjeda committed Aug 8, 2023
1 parent f72ef0c commit f6b20d2
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Sources/SwiftExtended/Optional.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,25 @@ public extension Optional {
.flatMap(transform)
}
}

public extension Optional where Wrapped: Equatable {
/// Checks if the value is wrapped within the `Optional` type.
/// - Parameter value: The value to search for.
/// - Returns: Whether the given value is wrapped in the `Optional` type.
func contains(_ value: Wrapped) -> Bool {
self == value
}
}

public extension Optional where Wrapped: Collection, Wrapped.Element: Equatable {
/// Checks if the value is present in the `Collection` wrapped within the `Optional` type.
/// - Parameter element: The value to search for.
/// - Returns: Whether the given value is present in the `Collection` wrapped in the `Optiona` type.
func contains(_ element: Wrapped.Element) -> Bool {
guard let collection = self else {
return false
}
return collection
.contains(where: \.self == element)
}
}
41 changes: 41 additions & 0 deletions Tests/SwiftExtendedTests/OptionalTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,45 @@ final class OptionalTests: XCTestCase {
.filter(where: \.self < numberTwo, then: String.init)
)
}

func testContains() {
// given
let letterA = "a"
let letterD = "d"
let lettersABC: [String] = ["a", "b", "c"]

// then
XCTAssertTrue(
Optional<String>
.some(letterA)
.contains(letterA)
)
XCTAssertFalse(
Optional<String>
.some(letterA)
.contains(letterD)
)
XCTAssertFalse(
Optional<String>
.none
.contains(letterA)
)

// also
XCTAssertTrue(
Optional<[String]>
.some(lettersABC)
.contains(letterA)
)
XCTAssertFalse(
Optional<[String]>
.some(lettersABC)
.contains(letterD)
)
XCTAssertFalse(
Optional<[String]>
.none
.contains(letterA)
)
}
}

0 comments on commit f6b20d2

Please sign in to comment.