Avatar
Key Path Expressions as FunctionsのProposalに載ってるコードの例がコンパイル通らない・・・ [1, nil, 3, nil, 5].compactMap(\.self) self-keypath-as-function.swift:1:32: error: cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int?) throws -> ElementOfResult?' [1, nil, 3, nil, 5].compactMap(\.self) ^ self-keypath-as-function.swift:1:21: error: generic parameter 'ElementOfResult' could not be inferred [1, nil, 3, nil, 5].compactMap(\.self) ^ Swift.Sequence:2:28: note: in call to function 'compactMap' @inlinable public func compactMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] ^ self-keypath-as-function.swift:1:32: error: cannot infer key path type from context; consider explicitly specifying a root type [1, nil, 3, nil, 5].compactMap(\.self) ^ <#Root#> 推論に問題がありそう?
7:55 AM
最初、\.self が対応してないのかと思ったけど、↓だと通る。 let values: [Int] = [2, 3, 5] let convert: (Int) -> Int = \.self let result: [Int] = values.map(convert) print(result)