且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift-如何从数组中找到最大的值并确定它来自哪个数组

更新时间:2023-02-10 21:24:27

实际上,我认为问题在于返回变量名而不是值。您可以通过Swift字典来实现。示例代码如下:

Actually I think the issue is for return the variable name instead of the value. You can achieve it by Swift dictionary. Sample code is like:

let users1 = [
"amya": 1,
"amyb": 2,
"amyc": 10
]
let max = users1.values.maxElement()

func allKeysForValue<K, V : Equatable>(dict: [K : V], val: V) -> [K] {
    return dict.filter{ $0.1 == val }.map{ $0.0 }
}

let keys = allKeysForValue(users1, val: max!)
print(keys)

结果是: [amyc]

它将找到结果最大值来自哪个变量,并将变量名称作为键返回。

It will find which variable the result largest value came from and return the variable names as keys.