Swift 中有没有一种方法可以引用我在分支中打开的值?例如:
switch UIDevice.current.userInterfaceIdiom {
// cases
default:
fatalError("User interface idiom \(value) is not supported")
}
我正在考虑类似于 catch
block 中的隐式 error
引用的东西:
do {
// ...
} catch {
print(error) // 'error' is defined implicitly
}
当然,我可以自己创建一个变量,但我想避免这种情况。
最佳答案
没有内置变量,但您可以使用 case let
模式轻松地自己捕获值:
switch UIDevice.current.userInterfaceIdiom {
// cases
case let value:
fatalError("User interface idiom \(value) is not supported")
}
注意:这将匹配任何内容,因此它替换了 default
大小写,它应该是您的 switch
中的最后一个 case
。
您可以使用 where
子句来允许捕获除everything 之外的值:
switch 1 + 2 * 3 {
case let value where 0...9 ~= value:
print("The value \(value) is a single digit value")
case let value:
print("\(value) is not a single digit value.")
}
但在这种情况下,将值分配给 switch
之前的变量会更容易。
关于swift - 在分支中引用 switch 语句的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42766180/