Created
January 15, 2023 14:37
-
-
Save 1000copy/7cbc1b4205686ab689d88214b53e49b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src from:https://www.cnswift.org/error-handling | |
struct Item { | |
var price: Int | |
var count: Int | |
} | |
//定义异常-枚举是典型的为一组相关错误条件建模的完美配适类型,关联值还允许错误错误通讯携带额外的信息。比如说,这是你可能会想到的游戏里自动售货机会遇到的错误条件: | |
enum VendingMachineError: Error { | |
case invalidSelection | |
case insufficientFunds(coinsNeeded: Int) | |
case outOfStock | |
} | |
class VendingMachine { | |
var inventory = [ | |
"Candy Bar": Item(price: 12, count: 7), | |
"Chips": Item(price: 10, count: 4), | |
"Pretzels": Item(price: 7, count: 11) | |
] | |
var coinsDeposited = 0 | |
// 使用抛出函数传递错误 | |
func vend(_ name: String) throws { | |
guard let item = inventory[name] else { | |
// 抛出异常 | |
throw VendingMachineError.invalidSelection | |
} | |
guard item.count > 0 else { | |
// 抛出异常 | |
throw VendingMachineError.outOfStock | |
} | |
guard item.price <= coinsDeposited else { | |
//// 抛出带参数异常 | |
throw VendingMachineError.insufficientFunds(coinsNeeded: item.price - coinsDeposited) | |
} | |
coinsDeposited -= item.price | |
var newItem = item | |
newItem.count -= 1 | |
inventory[name] = newItem | |
print("Dispensing \(name)") | |
} | |
} | |
let favoriteSnacks = [ | |
"Alice": "Chips", | |
"Bob": "Licorice", | |
"Eve": "Pretzels", | |
] | |
//为了明确一个函数或者方法可以抛出错误,你要在它的声明当中的形式参数后边写上 throws关键字 | |
func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws { | |
let snackName = favoriteSnacks[person] ?? "Candy Bar" | |
try vendingMachine.vend(snackName) | |
} | |
let v = VendingMachine() | |
v.coinsDeposited = 888 | |
//使用 Do-Catch 处理错误 | |
do{ | |
// try v.vend("noexists") | |
try v.vend("Pretzels") | |
try v.vend("Pretzels") | |
try buyFavoriteSnack(person: "Alice", vendingMachine: v) | |
} catch VendingMachineError.invalidSelection { | |
print("Invalid Selection.") | |
} catch VendingMachineError.outOfStock { | |
print("Out of Stock.") | |
} catch VendingMachineError.insufficientFunds(let coinsNeeded) { | |
print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.") | |
} catch { | |
print("Unexpected error: \(error).") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment