簡體   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