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

compactMap has different semantics with closure than keyPath.

    XMLWordPrintable

    Details

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

      Xcode 11.6, Swift 5.2

      Description

      The following code compiles without a warning, even though the `compactMap()` is arguably a mistake and should be replaced by `map()`:

      struct Item {
          var text: String
      }
      
      let items = [Item(text: "foo")]
      
      let filteredItems = items.compactMap { $0.text }
      

      But if I replace the last line with:

      let filteredItems = items.compactMap(\.text)
      

      It fails with:

      Generic parameter 'ElementOfResult' could not be inferred
      Key path value type 'String' cannot be converted to contextual type 'ElementOfResult?'
      

      I'm not sure whether the better fix here would be for `compactMap { $0.text }` to produce a warning, or for `compactMap(\.text)` to silently succeed, but it definitely seems wrong that these aren't consistent.

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            nicklockwood Nick Lockwood
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Dates

              Created:
              Updated: