我知道Enum的用法如下,那么Array或Dictionary呢? enum VendingMachineError: Error { case invalidSelection case insufficientFunds(coinsNeeded: Int) case outOfStock }throw VendingMachineError.insufficientFunds(coinsNeeded: 5) 可以使
enum VendingMachineError: Error { case invalidSelection case insufficientFunds(coinsNeeded: Int) case outOfStock } throw VendingMachineError.insufficientFunds(coinsNeeded: 5)可以使用符合Error协议的任何类型.如果你真的想要
抛出一个数组,然后声明符合协议就足够了:
extension Array: Error {} do { throw [1, 2, 3] } catch { print("Failed:", error) // Failed: [1, 2, 3] }
这是更现实的例子,使用struct来抛出
附加信息的错误(简化示例来自
Swift 3 errors with additional data):
struct ParserError: Error, LocalizedError { let line: Int public var errorDescription: String? { return "Parser error at line \(line)" } } func parse() throws { throw ParserError(line: 13) } do { try parse() } catch let error { print(error.localizedDescription) }
输出:
Parser error at line 13