在catch表达式中,let这个词的目的是什么?

问题描述 投票:2回答:3

在开头的“快速编程语言”一书中,他们有以下例子

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的用途是什么。

swift syntax keyword
3个回答
7
投票

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

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一样:

您可以使用switch语句检查不同的条形码类型,类似于使用Switch语句匹配枚举值中的示例。但是,这次,相关值将作为switch语句的一部分提取。您将每个关联值提取为常量(使用let前缀)或变量(使用var前缀)以在switch case的正文中使用


1
投票

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

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)")
}

1
投票

let关键字的用途是用于创建常量变量。

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

在这个例子中,无论发现什么ingredients被丢失,都将被抛出,并且catch SandwichError.missingIngredients(let ingredients)将在ingredients中接收它们以处理错误。

© www.soinside.com 2019 - 2024. All rights reserved.