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

Improve AnyError support in Result.init(attempt:) #223

Merged
merged 2 commits into from
May 15, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably only be if error isn't an AnyError? (Can you add a test for that?)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that is already covered here:

Result/Result/Result.swift

Lines 183 to 187 in 65d0c81

if let anyError = error as? AnyError {
self = anyError
} else {
self.error = error
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

I didn't realize that.

error = AnyError(error)
}
self = .failure(error as! Error)
}
}
Expand Down
8 changes: 8 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