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

[3.x] Improve AnyError support in Result.init(attempt:) #224

Merged
merged 2 commits into from
May 16, 2017
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
5 changes: 4 additions & 1 deletion Result/Result.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ public enum Result<T, Error: Swift.Error>: ResultProtocol, CustomStringConvertib
public init(attempt f: () throws -> T) {
do {
self = .success(try f())
} catch {
} catch var error {
if Error.self == AnyError.self {
error = AnyError(error)
}
self = .failure(error as! Error)
}
}
Expand Down
21 changes: 21 additions & 0 deletions Tests/ResultTests/ResultTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,14 @@ final class ResultTests: XCTestCase {
XCTAssert(result.error == error)
}

func testTryCatchWithFunctionThrowingNonAnyErrorCanProducesAnyErrorFailures() {
let nsError = NSError(domain: "", code: 0)
let function: () throws -> String = { throw nsError }

let result: Result<String, AnyError> = Result(attempt: function)
XCTAssert(result.error == AnyError(nsError))
}

func testMaterializeProducesSuccesses() {
let result1: Result<String, AnyError> = materialize(try tryIsSuccess("success"))
XCTAssert(result1 == success)
Expand Down Expand Up @@ -225,6 +233,19 @@ final class NoErrorTests: XCTestCase {
}
}

final class AnyErrorTests: XCTestCase {
static var allTests: [(String, (AnyErrorTests) -> () throws -> Void)] {
return [ ("testAnyError", testAnyError) ]
}

func testAnyError() {
let error = Error.a
let anyErrorFromError = AnyError(error)
let anyErrorFromAnyError = AnyError(anyErrorFromError)
XCTAssertTrue(anyErrorFromError == anyErrorFromAnyError)
}
}


// MARK: - Fixtures

Expand Down