Swift: case foo (let bar): 没有指定类型或赋值?

4
在Swift中,我了解到“let”定义一个常量。没问题。所以“let foo = 42”和“let foo: Int”是有意义的。但是我看到有几个例子只写了“let foo”,没有赋值或类型说明。例如,“case bar (let foo): ...”。
当这样的代码中仅出现“let foo”时,会发生什么呢?

你能展示一个可执行的例子吗? - Alexander
在代码的某个地方,会有一个类似于 case bar(Int) 的声明。 - Midhun MP
1个回答

3
这种符号用于绑定枚举的关联值。
例如,可以这样使用:
let anOptionalInt: Int? = 15

switch (anOptionalInt) {
case .Some(let wrappedValue):
    print(wrappedValue)

case .None:
    print("the optional is nil")
}

这个可以工作的原因是Optional 是一个枚举。第一个表达式可以写成:
let anOptionalInt: Optional<Int> = Optional.Some(15)

有两种情况: .Some.None。在 .Some 情况下,有一个关联值,称为 Wrapped,而 .None 情况没有关联值。

实际上,Optional.Nonenil 相同。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接