作者:白骨精哥哥_350 | 来源:互联网 | 2022-10-31 17:22
在《快速编程语言》一书中,他们有以下示例
func makeASandwich() throws {
// ...
}
do {
try makeASandwich()
eatASandwich()
} catch SandwichError.outOfCleanDishes {
washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
buyGroceries(ingredients)
}
我想知道的是生产线
catch SandwichError.missingIngredients(let ingredients)
具体的语法 (let ingredients)
在我看来,他们似乎在函数调用中使用了let一词,但也许我弄错了。无论如何,我想知道let的目的是什么。
1> Martin R..:
它是“值绑定模式”(在“枚举案例模式”内部)。
SandwichError
是带有“关联值”的枚举,例如
enum SandwichError: Error {
case outOfCleanDishes
case missingIngredients([String])
}
每个catch
关键字后面都有一个模式,如果SandwichError.missingIngredients
抛出错误,
throw SandwichError.missingIngredients(["Salt", "Pepper"])
然后
catch SandwichError.missingIngredients(let ingredients)
匹配,并且局部变量ingredients
绑定到["Salt", "Pepper"]
catch块的关联值。
它的工作原理基本上与使用Switch语句匹配枚举值:
您可以使用switch语句检查不同的条形码类型,类似于将枚举值与Switch语句匹配中的示例。但是,这次,关联值被提取为switch语句的一部分。您可以将每个关联的值提取为一个常量(带有let前缀)或一个变量(带有var前缀),以便在开关盒的主体内使用