File tree Expand file tree Collapse file tree 2 files changed +27
-0
lines changed Expand file tree Collapse file tree 2 files changed +27
-0
lines changed Original file line number Diff line number Diff line change @@ -690,6 +690,16 @@ public extension CocoaError {
690
690
}
691
691
}
692
692
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
+
693
703
extension CocoaError . Code {
694
704
}
695
705
Original file line number Diff line number Diff line change @@ -30,6 +30,7 @@ class TestNSError : XCTestCase {
30
30
( " test_CustomNSError_errorCode " , test_CustomNSError_errorCode) ,
31
31
( " test_CustomNSError_errorCodeRawInt " , test_CustomNSError_errorCodeRawInt) ,
32
32
( " test_CustomNSError_errorCodeRawUInt " , test_CustomNSError_errorCodeRawUInt) ,
33
+ ( " test_errorConvenience " , test_errorConvenience)
33
34
]
34
35
}
35
36
@@ -88,4 +89,20 @@ class TestNSError : XCTestCase {
88
89
89
90
XCTAssertEqual ( SwiftError . fortyTwo. errorCode, 42 )
90
91
}
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
+ }
91
108
}
You can’t perform that action at this time.
0 commit comments