swift - 在分支中引用 switch 语句的值

标签 swift

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/

相关文章:

Swift assert 无论如何打印字符串中的变量

macos - NSButton 改变宽度

json - 忽略 Codable 对象中的非 Codable 可选属性

swift - 如何在Xcode6中将响应数据转换为字符串

ios - 解除 UISearchBar 键盘后取消按钮消失

swift - 无法用闭包推断通用参数 'T'

swift - 如何借助 NSPredicate 使用自定义对象数组实现搜索?

ios - 协议(protocol)不会在 swift Ios 中调用

swift - macOS Mojave 无法使用 Swift 4 找到/var/db/DetachedSignatures

ios - swift3、Xcode 8.3 导航设置 titleTextAttributes 失败