Swift:分解"case let..."语句
Swift: Decompose "case let..." statement
几天前,我发布了一个Swift问题(),很快就得到了漂亮的答案。从那以后, 我一直在脑海中分解这句话:
case let word where excludedWords.contains(word):
被Swift解析执行。在我看来,首先评估 'let word...' 部分,对于 excludedWords 中出现的每个单词,Swift 将其传回案例进行评估。我没有找到任何文档,无论是 Apple 的还是其他的,都可以准确解释它是如何工作的。
有人可以详细解释一下这个结构在 Swift 中的工作原理吗?
来自 language reference(跳转到 Switch 语句部分):
A switch
case can optionally contain a where clause after each pattern. A where
clause is introduced by the where
keyword followed by an expression, and is used to provide an additional condition before a pattern in a case is considered matched to the control expression. If a where
clause is present, the statements within the relevant case are executed only if the value of the control expression matches one of the patterns of the case and the expression of the where
clause evaluates to true
.
我将在此处包含您的其他问题的答案以供参考:
switch eachWord {
case let word where excludedWords.contains(word):
// Do Something
default:
// Do another thing
}
执行过程如下:
let word = eachWord
- 测试是否
excludedWords.contains(word) == true
- 如果是,执行分支。否则,转到默认分支
几天前,我发布了一个Swift问题(
case let word where excludedWords.contains(word):
被Swift解析执行。在我看来,首先评估 'let word...' 部分,对于 excludedWords 中出现的每个单词,Swift 将其传回案例进行评估。我没有找到任何文档,无论是 Apple 的还是其他的,都可以准确解释它是如何工作的。
有人可以详细解释一下这个结构在 Swift 中的工作原理吗?
来自 language reference(跳转到 Switch 语句部分):
A
switch
case can optionally contain a where clause after each pattern. Awhere
clause is introduced by thewhere
keyword followed by an expression, and is used to provide an additional condition before a pattern in a case is considered matched to the control expression. If awhere
clause is present, the statements within the relevant case are executed only if the value of the control expression matches one of the patterns of the case and the expression of thewhere
clause evaluates totrue
.
我将在此处包含您的其他问题的答案以供参考:
switch eachWord {
case let word where excludedWords.contains(word):
// Do Something
default:
// Do another thing
}
执行过程如下:
let word = eachWord
- 测试是否
excludedWords.contains(word) == true
- 如果是,执行分支。否则,转到默认分支