7

I have the following enum:

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

And the following property definition:

var exampleProperty: ExampleEnum!

prior to swift 4.2 I was using the following switch statement:

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
}

Since switching to swift 4.2 this switch statement gives me the error:

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

I find this odd because I have clearly defined the type with an exclamation mark to implicitly unwrap the optional. However it seems not to be doing that. In order to make the error go away I need to perform the switch as follows:

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

What I did above was unwrap the exampleProperty variable again even though the definition is implicitly unwrapped and also remove the default from the switch.

Just wondering why this change in swift 4.2? Is it a change in the switch statement or why is this unwrapping required again. It seems redundant?

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
alionthego
  • 8,508
  • 9
  • 52
  • 125
  • 1
    Please read [Reimplementation of Implicitly Unwrapped Optionals](https://swift.org/blog/iuo/) – vadian Sep 26 '18 at 06:13
  • Thanks for the useful reference. I guess implicitly unwrapped optionals are now treated differently. Not sure I fully understand how the difference effects the switch statement but certainly it has to do with the new treatment of implicitly unwrapped optionals. Thanks. – alionthego Sep 29 '18 at 22:55

1 Answers1

0

for me it worke

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")
  }
}

but I am still confused, if we have force wrapped then why we need this
any suggestion will be appreciated

Sultan Ali
  • 2,497
  • 28
  • 25