Skip to content

Commit acff1e2

Browse files
ikesyoparkera
authored andcommitted
Fix (nsError as Error).localizedDescription output (#989)
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 3481ca0 commit acff1e2

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
@@ -288,7 +288,11 @@ public extension Error where Self : CustomNSError {
288288
public extension Error {
289289
/// Retrieve the localized description for this error.
290290
var localizedDescription: String {
291-
let defaultUserInfo = _swift_Foundation_getErrorDefaultUserInfo(self) as! [String : Any]
291+
if let nsError = self as? NSError {
292+
return nsError.localizedDescription
293+
}
294+
295+
let defaultUserInfo = _swift_Foundation_getErrorDefaultUserInfo(self) as? [String : Any]
292296
return NSError(domain: _domain, code: _code, userInfo: defaultUserInfo).localizedDescription
293297
}
294298
}

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)