Skip to content

Commit d0bb1af

Browse files
weichselparkera
authored andcommitted
Sync stdlib CocoaError convenience method (#1420)
* Synced missing CocoaError convenience method from Swift stdlib * Added a test case for CocoaError convenience method
1 parent 0027637 commit d0bb1af

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

Foundation/NSError.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -690,6 +690,16 @@ public extension CocoaError {
690690
}
691691
}
692692

693+
public extension CocoaError {
694+
public static func error(_ code: CocoaError.Code, userInfo: [AnyHashable: Any]? = nil, url: URL? = nil) -> Error {
695+
var info: [String: Any] = userInfo as? [String: Any] ?? [:]
696+
if let url = url {
697+
info[NSURLErrorKey] = url
698+
}
699+
return NSError(domain: NSCocoaErrorDomain, code: code.rawValue, userInfo: info)
700+
}
701+
}
702+
693703
extension CocoaError.Code {
694704
}
695705

TestFoundation/TestNSError.swift

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ class TestNSError : XCTestCase {
3030
("test_CustomNSError_errorCode", test_CustomNSError_errorCode),
3131
("test_CustomNSError_errorCodeRawInt", test_CustomNSError_errorCodeRawInt),
3232
("test_CustomNSError_errorCodeRawUInt", test_CustomNSError_errorCodeRawUInt),
33+
("test_errorConvenience", test_errorConvenience)
3334
]
3435
}
3536

@@ -88,4 +89,20 @@ class TestNSError : XCTestCase {
8889

8990
XCTAssertEqual(SwiftError.fortyTwo.errorCode, 42)
9091
}
92+
93+
func test_errorConvenience() {
94+
let error = CocoaError.error(.fileReadNoSuchFile, url: URL(fileURLWithPath: #file))
95+
96+
if let nsError = error as? NSError {
97+
XCTAssertEqual(nsError._domain, NSCocoaErrorDomain)
98+
XCTAssertEqual(nsError._code, CocoaError.fileReadNoSuchFile.rawValue)
99+
if let filePath = nsError.userInfo[NSURLErrorKey] as? URL {
100+
XCTAssertEqual(filePath, URL(fileURLWithPath: #file))
101+
} else {
102+
XCTFail()
103+
}
104+
} else {
105+
XCTFail()
106+
}
107+
}
91108
}

0 commit comments

Comments
 (0)