我知道Enum的用法如下,那么数组或字典呢?
enum VendingMachineError: Error {
case invalidSelection
case insufficientFunds(coinsNeeded: Int)
case outOfStock
}
throw VendingMachineError.insufficientFunds(coinsNeeded: 5)
答案 0 :(得分:6)
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