Uploaded image for project: 'Swift'
  1. Swift
  2. SR-1258

switch on invalid rawValue results takes first case



    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Done
    • Component/s: Compiler
    • Environment:

      The above code shows the Swift behaviour in the Playground.

      It hit the issue in real use (see above link) when running in the iOS 8 simulator with my application build in Xcode 7.3 with the iOS 9 SDK.


      When some an enum with a rawValue type actually has a raw value outside of the valid range and there is no default in the switch type the first case is taken and there is no runtime error or crash reported. This is dangerous behaviour admittedly requiring an error to have been made (in non-Swift code usually) to cause the invalid value to exist but even the biggest and fruitiest of companies has been known to make such mistakes (zero value NSFetchedResultsChangeType received|http://stackoverflow.com/a/32978387/1476206]).

      for i in -2..<8 {
      let changeType:NSFetchedResultsChangeType = unsafeBitCast(i, NSFetchedResultsChangeType.self)
      switch changeType {
      case .Move:
          print("Move - \(changeType.rawValue)")
      case .Update:
          print("Update - \(changeType.rawValue)")
      case .Insert:
          print("Insert - \(changeType.rawValue)")
      case .Delete:
          print("Delete - \(changeType.rawValue)")
      /* Move - 18446744073709551614
       Move - 18446744073709551615
       Move - 0
       Insert - 1
       Delete - 2
       Move - 3
       Update - 4
       Move - 5
       Move - 6
       Move - 7 */

      The unsafeBitCast is used to force the error within Swift but the more likely real case in an error in code written in an unsafe language being returned or passed into Swift code.

      I think the very least that should be done by Swift is to raise an assertion in these situations and probably a PreConditionFailure.




            • Assignee:
              josephlord Joseph Lord
            • Votes:
              0 Vote for this issue
              4 Start watching this issue


              • Created: