From 076301dd9238532a4752b646fbc695cf141944ed Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Tue, 16 May 2017 02:41:45 +0900 Subject: [PATCH 1/2] Improve AnyError support in `Result.init(attempt:)` --- Result/Result.swift | 5 ++++- Tests/ResultTests/ResultTests.swift | 8 ++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Result/Result.swift b/Result/Result.swift index b08ea8e..c49d526 100644 --- a/Result/Result.swift +++ b/Result/Result.swift @@ -31,7 +31,10 @@ public enum Result: 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) } } diff --git a/Tests/ResultTests/ResultTests.swift b/Tests/ResultTests/ResultTests.swift index 5a5a8f5..482328b 100644 --- a/Tests/ResultTests/ResultTests.swift +++ b/Tests/ResultTests/ResultTests.swift @@ -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 = Result(attempt: function) + XCTAssert(result.error == AnyError(nsError)) + } + func testMaterializeProducesSuccesses() { let result1: Result = materialize(try tryIsSuccess("success")) XCTAssert(result1 == success) From 87dfe7f59e37d0e57a2137348967dc4939ef9d02 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Tue, 16 May 2017 03:12:37 +0900 Subject: [PATCH 2/2] Add a simple AnyError test --- Tests/ResultTests/ResultTests.swift | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Tests/ResultTests/ResultTests.swift b/Tests/ResultTests/ResultTests.swift index 482328b..04229ee 100644 --- a/Tests/ResultTests/ResultTests.swift +++ b/Tests/ResultTests/ResultTests.swift @@ -233,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