Swift 有没有办法引用我在分支中打开的值?例如:
switch UIDevice.current.userInterfaceIdiom {
// cases
default:
fatalError("User interface idiom \(value) is not supported")
}
我正在考虑类似于隐含的东西error
里面参考catch
block:
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
这应该是最后一个案例case
在你的switch
.
您可以使用where
子句允许捕获除一切:
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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)