Swift catch表达式中let这个词的用途是什么?

Swift catch表达式中let这个词的用途是什么?,swift,syntax,keyword,Swift,Syntax,Keyword,在一开始的《swift编程语言》一书中,他们有以下示例 func makeASandwich() throws { // ... } do { try makeASandwich() eatASandwich() } catch SandwichError.outOfCleanDishes { washDishes() } catch SandwichError.missingIngredients(let ingredients) { buyGroce

在一开始的《swift编程语言》一书中,他们有以下示例

func makeASandwich() throws {
    // ...
}

do {
    try makeASandwich()
    eatASandwich()
} catch SandwichError.outOfCleanDishes {
    washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
    buyGroceries(ingredients)
}
我想知道的是线路

catch SandwichError.missingIngredients(let ingredients)
特别是语法
(让成分)


在我看来,他们在函数调用中使用了let这个词,但也许我弄错了。无论如何,我想知道word let的用途是什么。

它是一种“值绑定模式”(在“枚举案例模式”中)

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

enum SandwichError: Error {
     case outOfCleanDishes
     case missingIngredients([String])
}
每个
catch
关键字后面都有一个模式,如果出现
SandwichError.missingElements
错误,则抛出

throw SandwichError.missingIngredients(["Salt", "Pepper"])
然后

匹配,局部变量
成分
绑定到catch块的关联值
[“Salt”,“Pepper”]

其基本工作原理如下:

可以使用switch语句检查不同的条形码类型,类似于将枚举值与switch语句匹配的示例。但是,这一次,关联的值被提取为switch语句的一部分。将每个关联值提取为常量(带let前缀)或变量(带var前缀),以便在开关盒的主体中使用

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

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

let
关键字用于创建常量变量

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


在本例中,将抛出发现缺失的任何
成分
,并且
捕获三明治错误。缺失成分(让成分)
将在
成分
中接收它们,用于处理错误。

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

enum SandwichError: Error {
     case outOfCleanDishes
     case missingIngredients([String])// associated value
}
将枚举值与Switch语句匹配时 将每个关联值提取为常量(带let前缀)或变量(带var前缀),以便在交换机外壳的主体中使用

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

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

请阅读Swift语言指南,实际阅读整个指南。这是值得的。读一下这个,谢谢瓦迪安。这正是我在这里遇到的困难。我不理解枚举关联的值。一旦我阅读了你链接到的文本,一切都变得清晰了。我编辑了标题(和标签),请检查这是否仍然反映了你的意图。@Martin R更好:)因此,如果我没有使用let这个词,也就是说,如果我只使用catch SandwichError.MissingElements(配料),然后会容纳一个称为成分的局部变量。或者这是一个语法错误,我会被迫写一些类似SandwichError.MissingElements(var Components)的东西吗?@BobUeland,尝试将它与普通变量声明和初始化联系起来<代码>捕获三明治错误。MissingElements(Components)不声明
成分
,编译器将不知道这是什么。我们需要申报这是什么。回答你的第二个问题,如果你使用
var成分
,如果你根本没有变异
成分
,你会得到警告。因此,使用“让成分”是有意义的。