let 在 catch 表达式中的作用是什么?

What is the purpose of the word let inside a catch expression?

在书"the swift programming language"开头,他们有下面的例子

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 这个词的目的是什么。

这是一个“值绑定模式”(在“枚举案例模式”内部)。

SandwichError 是一个带有“关联值”的枚举,类似于

enum SandwichError: Error {
     case outOfCleanDishes
     case missingIngredients([String])
}

每个 catch 关键字后跟一个模式,如果使用

抛出 SandwichError.missingIngredients 错误
throw SandwichError.missingIngredients(["Salt", "Pepper"])

然后

catch SandwichError.missingIngredients(let ingredients)

匹配并且局部变量 ingredients 绑定到 catch 块的关联值 ["Salt", "Pepper"]

它的工作原理与 Matching Enumeration Values with a Switch Statement 基本相同:

You can check the different barcode types using a switch statement, similar to the example in Matching Enumeration Values with a Switch Statement. This time, however, the associated values are extracted as part of the switch statement. You extract each associated value as a constant (with the let prefix) or a variable (with the var prefix) for use within the switch case’s body

let关键字的目的是用来创建常量变量。

在此上下文中,let 关键字用于创建局部常量 ingredients,用于容纳作为错误抛出的预期输入参数。

在这个例子中,无论ingredients被发现丢失,都会被抛出,catch SandwichError.missingIngredients(let ingredients)会在ingredients中接收它们,用于处理错误。

swift 中的枚举可以指定任何类型的关联值与每个不同的 case 值一起存储

enum SandwichError: Error {
     case outOfCleanDishes
     case missingIngredients([String])// associated value
}

将枚举值与 Switch 语句匹配时 将每个关联值提取为常量(带有 let 前缀)或变量(带有 var 前缀)以在 switch case 的正文中使用

var error = SandwichError.missingIngredients(["a", "b"])

switch productBarcode {
case . outOfCleanDishes:
    print("Out of clean dishes!")
case . missingIngredients(let ingredients):
    print("Missing \(ingredients)")
}