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

Rom*_*man 2 swift swift5 swift-keypath

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

错误:

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

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

也许用compactMap的例子会更香))

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

错误:

无法将“WritableKeyPath<_, _>”类型的值转换为预期的参数类型“(Int?) throws -> ElementOfResult?”

Mar*_*n R 6

为什么不起作用?好像应该。

你是对的。你的两个例子都应该编译,因为

事实上,后一个提案明确提到了一个与您相似的例子。但是,这不能编译(从 Xcode 11.7 和 Xcode 12 beta 开始):

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

那是一个错误。它已经被报道为

错误报告提到自定义扩展作为可能的解决方法:

extension Optional { var mySelf: Self { self } }

[1, nil, 3, nil, 5].compactMap(\.mySelf)
Run Code Online (Sandbox Code Playgroud)