Skip to content

[SR-13347] compactMap has different semantics with closure than keyPath. #55787

@nicklockwood

Description

@nicklockwood
Previous ID SR-13347
Radar None
Original Reporter @nicklockwood
Type Bug
Environment

Xcode 11.6, Swift 5.2

Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Bug
Assignee None
Priority Medium

md5: 0300b2587bde2e6fea9e7b74b21a2d20

Issue 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itself

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions