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

Enum Type Inference produces unexpected result with optional

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Duplicate
    • Component/s: Compiler
    • Labels:
      None
    • Environment:

      Xcode Version 10.2.1 (10E1001)

      Swift 5.0

      Description

      var s1:UITableViewCell.SelectionStyle? = .none

       

      expected:

      s1 == UITableViewCell.SelectionStyle.none

      actual:

      s1 == Optional.none == nil

      This just caught me out in a project, and it seems like confusing behaviour. I understand that it will generate a warning in swift 5.1

      quoting the Swift guide:

      The type of directionToHead is inferred when it's initialized with one of the possible values of CompassPoint. Once directionToHead is declared as a CompassPoint, you can set it to a different CompassPoint value using a shorter dot syntax:

      wheras perhaps it should have a more complicated

      ... you can set it to a different CompassPoint value using a shorter dot syntax - except watch out for variables that are optional, and where the case is called .none, because that will clash with the Optional (which is actually implemented as an enum) and select Optional.none from the outer type

      my feeling is that this is the kind of 'gotcha' which languages should avoid. If you have to have a deep understanding of how the language is implemented to understand a special case when assigning a variable - then that is suboptimal

       

      possible ideas for fixes:

      1) change the precedence

      when assigning to 

      var s1:UITableViewCell.SelectionStyle?

      it feels to me that s1 is 'more strongly' identified  UITableViewCell.SelectionStyle rather than Optional.

      this may have broader unpleasant consequences though

      2) change the case name within Optional so that it clashes less often

      perhaps Optional.none -> Optional.nil would seem nice (although nil is not currently allowed as a case name)

      otherwise Optional.null, Optional.nothing, Optional.empty ???

       

       

       

       

       

       

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned
              Reporter:
              ConfusedVorlon Rob Jonson
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: