【问题标题】:swift 4.2 Enum case ' ' not found in type '?' Requirement in switch statement to redundantly unwrap an implicitly unwrapped optionalswift 4.2 Enum case '' not found in type '?' switch 语句中要求冗余解包隐式解包的可选
【发布时间】:2019-03-01 15:56:50
【问题描述】:

我有以下枚举:

enum ExampleEnum {
    case one
    case two
    case three
    case four  
}

以及以下属性定义:

var exampleProperty: ExampleEnum!

在 swift 4.2 之前,我使用以下 switch 语句:

switch self.exampleProperty {
    case .one:
        print("case one")
    case .two:
        print("case two")
    case .three:
        print("case three")
    case .four:
        print("case four")
    default:
        break
}

自从切换到 swift 4.2 后,这个 switch 语句给了我错误:

Enum case 'one' not found in type 'ExampleEnum?'

我觉得这很奇怪,因为我已经用感叹号清楚地定义了类型,以隐式解开可选项。但是,它似乎没有这样做。为了使错误消失,我需要按如下方式执行切换:

switch self.exampleProperty! {
    case .one:
        print("case one")
    case .two:
        print("case two")
    case .three:
        print("case three")
    case .four:
        print("case four")
}

我在上面所做的是再次解开 exampleProperty 变量,即使定义被隐式解包,并且还从开关中删除了默认值。

只是想知道为什么 swift 4.2 会发生这种变化?是 switch 语句的变化还是为什么再次需要这种展开。好像是多余的?

【问题讨论】:

  • 感谢您的有用参考。我猜隐式展开的选项现在被区别对待了。不确定我是否完全理解差异如何影响 switch 语句,但肯定与隐式展开选项的新处理有关。谢谢。

标签: ios swift switch-statement xcode10 swift4.2


【解决方案1】:

对我来说很有效

if let myEnumCase = self.exampleProperty {
      switch myEnumCase {
      case .one:
        print("case one")
      case .two:
        print("case two")
      case .three:
        print("case three")
      case .four:
        print("case four")
  }
}

但我仍然很困惑,如果我们有强制包装那么我们为什么需要这个
任何建议将不胜感激

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    相关资源
    最近更新 更多