Skip to content

Commit

Permalink
Fix (nsError as Error).localizedDescription output (#967)
Browse files Browse the repository at this point in the history
Because NSError is not `LocalizedError` and `_swift_Foundation_getErrorDefaultUserInfo` does not handle NSError instances, `(nsError as Error).localizedDescription` didn't return expected output. So let's handle NSError case in `Error.localizedDescription` implementation.
  • Loading branch information
ikesyo authored and parkera committed May 17, 2017
1 parent 881acbb commit 1b58627
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
6 changes: 5 additions & 1 deletion Foundation/NSError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,11 @@ public extension Error where Self : CustomNSError {
public extension Error {
/// Retrieve the localized description for this error.
var localizedDescription: String {
let defaultUserInfo = _swift_Foundation_getErrorDefaultUserInfo(self) as! [String : Any]
if let nsError = self as? NSError {
return nsError.localizedDescription
}

let defaultUserInfo = _swift_Foundation_getErrorDefaultUserInfo(self) as? [String : Any]
return NSError(domain: _domain, code: _code, userInfo: defaultUserInfo).localizedDescription
}
}
Expand Down
7 changes: 7 additions & 0 deletions TestFoundation/TestNSError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class TestNSError : XCTestCase {
static var allTests: [(String, (TestNSError) -> () throws -> Void)] {
return [
("test_LocalizedError_errorDescription", test_LocalizedError_errorDescription),
("test_NSErrorAsError_localizedDescription", test_NSErrorAsError_localizedDescription),
]
}

Expand All @@ -33,4 +34,10 @@ class TestNSError : XCTestCase {
let error = Error()
XCTAssertEqual(error.localizedDescription, "error description")
}

func test_NSErrorAsError_localizedDescription() {
let nsError = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Localized!"])
let error = nsError as Error
XCTAssertEqual(error.localizedDescription, "Localized!")
}
}

0 comments on commit 1b58627

Please sign in to comment.