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

Improve inference of optional supertypes

    XMLWordPrintable

    Details

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

      Description

      If an array literal contains at least one element that is a nil literal and at least one other element that is of type T, the type checker will set the element type of the array to Optional<T>:

      let arr1 = [1, nil, 3]
      print(type(of: arr1)) 		// Array<Optional<Int>>
      
      struct S {}
      let arr2 = [S(), nil]
      print(type(of: arr2))		// Array<Optional<S>>
      

      This also works in other situations, where the type checker tries to find a common supertype of multiple expressions:

      let x1 = true ? 1 : nil
      print(type(of: x1))		// Optional<Int>
      
      struct S {}
      let x2 = false ? nil : S()
      print(type(of: x2))		// Optional<S>
      

      However, this currently only seems to work if T is a nominal type. If T is any other kind of type, there's a type error:

      let arr = [(1, "test"), nil, (2, "test")]	// error: type of expression is ambiguous without more context
      
      let c = { $0 * 2 }
      let x = true ? c : nil			// error: result values in '? :' expression have mismatching types '(Int) -> Int' and '_'
      

      There is no reason why this shouldn't work with other types as well.

        Attachments

          Activity

            People

            • Assignee:
              tonisuter Toni Suter
              Reporter:
              tonisuter Toni Suter
            • Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: