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

Casting through options has bugs and misleading warning

    XMLWordPrintable

    Details

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

      Description

      Normally in guard and if condition lists, you look up a value in a dictionary and conditionally cast:

      if let value = dict[key] as? T, ...

      The "as?" operator passes the Any? type through, and the lhs result is T, not T?. However, this doesn't happen when you conditionally cast T? to U, for example, when a dictionary is [AnyHashable: String]:

      guard let value = dict["Key"] as? NSString
      else

      { fatalError() }

      See error shown here http://i.imgur.com/SkXkk6o.jpg

      In this case, the compiler asserts that a cast from String? to an unrelated type NSString always fails. You can mitigate this by sticking an "Any" cast in the middle:

      guard let value = dict["Key"] as Any as? NSString
      else { fatalError() }

      Joe Groff: "This is a bug. 'String as NSString' works, and you can cast through Optionals 'T? as? U', so transitively this also works, despite the misleading warning. Please file a bug report if you haven't yet."

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              erica erica sadun
            • Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: