gpt4 book ai didi

swift - 如何找到与x相差最小的字典值[Swift]

转载 作者:行者123 更新时间:2023-11-30 10:44:10 24 4
gpt4 key购买 nike

使用 Swift,我正在尝试构建一个与 this answer 相同的复杂过滤器或排序。 ,但对于字典来说,它是值而不是数组。我的整数值也可以是任何整数值——没有限制。给定一个不在数组中的整数值(比如 X),我想找到它与 X 之间差异最小的数组元素:

let playerGuesses = ["Mike": 432, "Chrissy": 164]
let x = 222

数组版本给出的答案如下:

let closest = numbers.enumerated().min( by: { abs($0.1 - x) < abs($1.1 - x) } )!
print(closest.element) // 7
print(closest.offset) // 2

如何对字典值完成类似的操作?

最佳答案

基本上是一样的。只需删除 enumerated() 并使用 keyvalue 以及 closest 即可。

let playerGuesses = ["Mike": 432, "Chrissy": 164]
let x = 222
let closest = playerGuesses.min { abs($0.1 - x) < abs($1.1 - x) }
print(closest?.key, closest?.value)

min 闭包中,$x.0 是键,$x.1 是值。

关于swift - 如何找到与x相差最小的字典值[Swift],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56140157/

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