热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

catch表达式中的let的目的是什么?

如何解决《catch表达式中的let的目的是什么?》经验,为你挑选了1个好方法。

在《快速编程语言》一书中,他们有以下示例

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前缀),以便在开关盒的主体内使用


推荐阅读
author-avatar
白骨精哥哥_350
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有