4
let test = [4, 5, 3, 1, 3]
print(
    test.map { $0 }
)
print(
    test.map(\.self)  // Doesn't compile  
)

Error:

Type of expression is ambiguous without more context

Why doesn't it work? Seems like it should.
If isn't this way, how else can we rid of the ugly { $0 } here?

Maybe an example with compactMap will make more cense))

let test = [4, 5, nil, 3, 1, nil, 3]
print(
    test.compactMap { $0 }
)
print(
    test.compactMap(\.self)  // Doesn't compile  
)

Error:

Cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int?) throws -> ElementOfResult?'

9
  • 1
    How about writing your own identity function?
    – Sweeper
    Sep 4, 2020 at 2:59
  • @Sweeper That's an interesting idea))) But why doesn't KeyPath work here?
    – Roman
    Sep 4, 2020 at 3:02
  • 1
    From the way the docs is worded, it seems like \.self is somewhat of a special case, and is treated differently. It even has its own name, "the identity key path".
    – Sweeper
    Sep 4, 2020 at 3:05
  • 1
    It looks like a bug to me. According to SE-0249 Key Path Expressions as Functions (which is implemented in Swift 5.2) should let filtered = [1, nil, 3, nil, 5].compactMap(\.self) compile. But it does not (tested with Xcode 11 and 12 beta).
    – Martin R
    Sep 4, 2020 at 3:41
  • 2
    It is a bug: bugs.swift.org/browse/SR-12897
    – Martin R
    Sep 4, 2020 at 3:56

1 Answer 1

8

Why doesn't it work? Seems like it should.

You are right. Both of your examples should compile because

In fact the latter proposal explicitly mentions an example similar to yours. However, that does not compile (as of Xcode 11.7 and Xcode 12 beta):

[1, nil, 3, nil, 5].compactMap(\.self)
// error: generic parameter 'ElementOfResult' could not be inferred

That is a bug. It has already been reported as

The bug report mentions a custom extension as a possible workaround:

extension Optional { var mySelf: Self { self } }

[1, nil, 3, nil, 5].compactMap(\.mySelf)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.