Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Result.init(catching:) with async method #2060

Merged
merged 2 commits into from
Nov 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Sources/FoundationExtensions/Result+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,17 @@ extension Result where Success: OptionalType {
}

}

@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *)
extension Result where Failure == Swift.Error {

/// Equivalent to `Result.init(catching:)` but with an `async` closure.
init(catching block: () async throws -> Success) async {
do {
self = .success(try await block())
} catch {
self = .failure(error)
}
}

}
30 changes: 30 additions & 0 deletions Tests/UnitTests/FoundationExtensions/ResultExtensionsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,36 @@ class ResultExtensionsTests: TestCase {
})
}

@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *)
func testInitWithThrowingAsyncBlockReturningValue() async throws {
try AvailabilityChecks.iOS13APIAvailableOrSkipTest()

let expectedValue: Int = .random(in: 0..<100)

func asyncValue() async throws -> Int {
return expectedValue
}

let result: Result<Int, Swift.Error> = await .init(catching: { try await asyncValue() })
expect(result).to(beSuccess())
expect(result.value) == expectedValue
}

@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *)
func testInitWithThrowingAsyncBlockThrowingError() async throws {
try AvailabilityChecks.iOS13APIAvailableOrSkipTest()

let expectedError: ErrorCode = .customerInfoError

func asyncValue() async throws -> Int {
throw expectedError
}

let result: Result<Int, Swift.Error> = await .init(catching: { try await asyncValue() })
expect(result).to(beFailure())
expect(result.error).to(matchError(expectedError))
}

}

class ResultAsOptionalResultTest: TestCase {
Expand Down