以最简单的形式在map中应用KeyPath

问题描述

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

错误

表达式类型不明确,没有更多上下文

为什么不起作用?好像应该这样。
如果不是这样,我们还能在这里如何摆脱丑陋的{$ 0}?

也许带有compactMap的示例会带来更多好处))

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

错误

无法将类型为'WritableKeyPath <_>'的值转换为预期值 参数类型'(Int?)抛出-> ElementOfResult?'

解决方法

为什么不起作用?似乎应该如此。

您是对的。您的两个示例都应编译,因为

实际上,后一个建议明确提到了一个与您相似的示例。但是,它不能编译(从Xcode 11.7和Xcode 12 beta开始):

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

那是一个错误。据报道为

错误报告中提到了自定义扩展名,这是一种可能的解决方法:

extension Optional { var mySelf: Self { self } }

[1,5].compactMap(\.mySelf)