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?'
identity
function?\.self
is somewhat of a special case, and is treated differently. It even has its own name, "the identity key path".let filtered = [1, nil, 3, nil, 5].compactMap(\.self)
compile. But it does not (tested with Xcode 11 and 12 beta).