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

Runtime exception casting an Any? nil to a generic optional

    XMLWordPrintable

    Details

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

      Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1)
      Target: x86_64-apple-macosx10.9

      Description

      Summary

      An unexpected fatal error in a forced downcast from a nil to an optional generic type T, e.g. T = String?.

      • NOTE: Casting nil as Any before the forced downcast is a workaround to avoid the runtime fatal error. Perhaps this in itself is its own bug?
      • NOTE: This is similar to a previously reported and resolved bug: https://bugs.swift.org/browse/SR-912 — in this case, the input type is Any and not Any?.

      Code Example

      struct Cast<T> {
        // Crashes if `value` is `nil`
        func optional(_ value: Any?) {
          output(value as! T)
        }
      
        // Should be identical to `optional`, but it's not. Perhaps a separate bug here?
        func workaround(_ value: Any?) {
          output((value as Any) as! T)
        }
      
        private func output(_ value: T) {
          print(value as Any)
        }
      }
      
      let cast = Cast<String?>()
      
      let full: String? = "Hello"
      cast.optional(full as Any)   // Optional("Hello")
      cast.workaround(full as Any) // Optional("Hello")
      
      let empty: String? = nil
      cast.workaround(empty)      // nil
      cast.optional(empty)        // FATAL ERROR: unexpectedly found nil while unwrapping an Optional value
      

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                originaluser2 Hamish Knight
                Reporter:
                burgestrand Kim Burge Strand
              • Votes:
                0 Vote for this issue
                Watchers:
                4 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: