Skip to content

Commit

Permalink
feat: add the zip 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 81391bf commit 6ce8995
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Sources/SwiftExtended/Optional.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,30 @@ public extension Optional {
}
}

public extension Optional {
/// Combines (zips) the given value with the existing one - if any - to produce a tuple.
///
/// The tuple is only produced when both optional values contain a value; otherwise, it returns `Optional.none`.
///
/// ```swift
/// let credentials: Credentials? = usernameTextField
/// .text
/// .zip(with: passwordTextField.text)
/// .map { username, password in
/// Credentials(username: username, password: password)
/// }
/// ```
///
/// - Parameter other: The value to combine.
/// - Returns: A tuple containing the zipped values.
func zip<Other>(with other: Other?) -> (Wrapped, Other)? {
guard let self, let other else {
return nil
}
return (self, other)
}
}

public extension Optional where Wrapped: Equatable {
/// Checks if the value is wrapped within the `Optional` type.
/// - Parameter value: The value to search for.
Expand Down
29 changes: 29 additions & 0 deletions Tests/SwiftExtendedTests/OptionalTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,33 @@ final class OptionalTests: XCTestCase {
.contains(letterA)
)
}

func testZip() throws {
// given
let leftHandSideValue = 1
let rightHandSideValue = "A"

// when
let unzippedPair = try XCTUnwrap(
Optional
.some(leftHandSideValue)
.zip(with: Optional.some(rightHandSideValue))
)

// then
XCTAssertEqual(leftHandSideValue, unzippedPair.0)
XCTAssertEqual(rightHandSideValue, unzippedPair.1)

// and when
let nilDueToLeftHandSide = Optional<Int>
.none
.zip(with: Optional.some(rightHandSideValue))
let nilDueToRightHandSide = Optional
.some(leftHandSideValue)
.zip(with: Optional<String>.none)

// then
XCTAssertNil(nilDueToLeftHandSide)
XCTAssertNil(nilDueToRightHandSide)
}
}

0 comments on commit 6ce8995

Please sign in to comment.