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

flatMap returns wrong result with covariant transform closure

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Compiler
    • Labels:
    • Environment:

      Swift 2.1, OS X 10.11.3, Xcode 7.2.1

      Description

      Given the following snippet:

      var a: [Int?] = [1,2,nil]
      a = a.flatMap { (item: Int?) -> Int? in
          return item
      }
      print(a)
      

      I expect the return value to be [1,2,nil], but it returns [1,2] instead.

      My rationale is that the matching function is...

      extension SequenceType {
          @warn_unused_result
          public func flatMap<T>(@noescape transform: (Self.Generator.Element) throws -> T?) rethrows -> [T]
      }
      

      ... so the return type of flatMap must be [Int?] to match the type of a, that implies T is Int?. That means the return type of transform must be Int??. Our closure returning Int? is properly accepted as it is covariant [0]. However, my expectation is that if our closure returns .None it would be treated as .Some(.None) ultimately by the transform, since .None is a valid Int? for wrapping in Int??.

      [0]: Indeed, this code does not compile in 2.0, before closure covariance support was added.

        Attachments

          Activity

            People

            Assignee:
            Unassigned
            Reporter:
            ianterrell Ian Terrell
            Votes:
            1 Vote for this issue
            Watchers:
            2 Start watching this issue

              Dates

              Created:
              Updated: