Skip to content

Commit

Permalink
Result.init(catching:) with async method (#2060)
Browse files Browse the repository at this point in the history
I ended up not using this in my recent PR but it's a useful overload.
  • Loading branch information
NachoSoto authored Nov 23, 2022
1 parent f312fe1 commit 47143a8
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
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

0 comments on commit 47143a8

Please sign in to comment.