繁体   English   中英

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

[英]Apply KeyPath in map() in simplest form

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

错误:

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

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

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

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

错误:

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

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

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

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

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

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

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

extension Optional { var mySelf: Self { self } }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM