Skip to content

Commit 1b58627

Browse files
ikesyoparkera
authored andcommitted
Fix (nsError as Error).localizedDescription output (#967)
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.
1 parent 881acbb commit 1b58627

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

Foundation/NSError.swift

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,11 @@ public extension Error where Self : CustomNSError {
285285
public extension Error {
286286
/// Retrieve the localized description for this error.
287287
var localizedDescription: String {
288-
let defaultUserInfo = _swift_Foundation_getErrorDefaultUserInfo(self) as! [String : Any]
288+
if let nsError = self as? NSError {
289+
return nsError.localizedDescription
290+
}
291+
292+
let defaultUserInfo = _swift_Foundation_getErrorDefaultUserInfo(self) as? [String : Any]
289293
return NSError(domain: _domain, code: _code, userInfo: defaultUserInfo).localizedDescription
290294
}
291295
}

TestFoundation/TestNSError.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ class TestNSError : XCTestCase {
2222
static var allTests: [(String, (TestNSError) -> () throws -> Void)] {
2323
return [
2424
("test_LocalizedError_errorDescription", test_LocalizedError_errorDescription),
25+
("test_NSErrorAsError_localizedDescription", test_NSErrorAsError_localizedDescription),
2526
]
2627
}
2728

@@ -33,4 +34,10 @@ class TestNSError : XCTestCase {
3334
let error = Error()
3435
XCTAssertEqual(error.localizedDescription, "error description")
3536
}
37+
38+
func test_NSErrorAsError_localizedDescription() {
39+
let nsError = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Localized!"])
40+
let error = nsError as Error
41+
XCTAssertEqual(error.localizedDescription, "Localized!")
42+
}
3643
}

0 commit comments

Comments
 (0)