gpt4 book ai didi

swift - map(keyPath) 其中 keyPath 是一个变量

转载 作者:行者123 更新时间:2023-12-05 02:05:12 26 4
gpt4 key购买 nike

let arr = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
arr.map(\.0) // [1, 2, 3, 4, 5]

效果很好。但是下面的代码无法编译:

let keyPath = \(Int, Int).0
arr.map(keyPath)

Cannot convert value of type 'WritableKeyPath<(Int, Int), Int>' toexpected argument type '((Int, Int)) throws -> T'.
Generic parameter 'T' could not be inferred.

最佳答案

Array.map 需要一个带有签名的闭包 (Element) throws -> T

在 Swift 5.2 中,键路径被允许作为函数/闭包传入(这里是 evolution proposal ),但只能作为文字(至少,根据提议,它说“现在”,所以也许这个限制会被取消)。

为了克服这个问题,您可以在 Sequence 上创建一个接受关键路径的扩展:

extension Sequence {
func map<T>(_ keyPath: KeyPath<Element, T>) -> [T] {
return map { $0[keyPath: keyPath] }
}
}

(贷记:https://www.swiftbysundell.com/articles/the-power-of-key-paths-in-swift/)

然后你就可以做你想做的了:

let keyPath = \(Int, Int).0
arr.map(keyPath)

关于swift - map(keyPath) 其中 keyPath 是一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63764608/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com