SwiftError
SwiftError 允许您创建符合 Error、CustomNSError 和 LocalizedError 协议的错误,而无需声明您自己的错误类型。
便利设施
提供两个工具函数作为示例,演示如何通过利用错误类型来简化源代码。
-
cast<T, U>(_ subject: T) -> U
在处理远程API时,再也不必强制转换。相反,
let string = any as! String
变为let string = try cast(any) as String
-
unwrap<T>(_ optional: T?) -> T
在工作于遗留接口时,改写
let some = optional!
为let some = try unwrap(optional)
示例
- 编译示例
swiftc SwiftError/*.swift main.swift -o demo
- 运行示例
./demo
样本输出
Demo print output
-----------------
Undefined error -10001, demoThrow(), main.swift:L5
["key": "val", "float": 3.1, "int": 256]
Demo debugPrint output
----------------------
Undefined error -10001, demoThrow(), main.swift:L5
0 main 0x000000010f1be165 $S4main9demoThrowyyKF + 501
1 main 0x000000010f1bc96d main + 45
{
float = "3.1";
int = 256;
key = val;
}
Demo cast print output
----------------------
Unexpected String in place of Int -10000, demoCast(), main.swift:L22
Demo cast debugPrint output
---------------------------
Unexpected String in place of Int -10000, demoCast(), main.swift:L22
0 main 0x000000010f1bf015 $S4main4cast_4file8function4lineq_x_S2SSitKr0_lF + 1189
1 main 0x000000010f1be2f9 $S4main8demoCastyyKF + 217
2 main 0x000000010f1bca55 main + 277
Demo unwrap print output
------------------------
Unexpected nil for optional Any -9999, demoUnwrap(), main.swift:L40
Demo unwrap debugPrint output
-----------------------------
Unexpected nil for optional Any -9999, demoUnwrap(), main.swift:L40
0 main 0x000000010f1be9fb $S4main6unwrap_4file8function4linexxSg_S2SSitKlF + 891
1 main 0x000000010f1be464 $S4main10demoUnwrapyyKF + 212
2 main 0x000000010f1bcb3d main + 509