Swift-如何从数组中找到最大的值并确定它来自哪个数组 [英] Swift - How to find Largest value from an array and identify which array it came from

查看:59
本文介绍了Swift-如何从数组中找到最大的值并确定它来自哪个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    var amya = (1)
    var amyb = (2)
    var amyc = (3)
    var amyd = (3)
    var amye = (9)
    var amyf = (3)
    var amyg = (4)
    var amyh = (4)
    var amyi = (10)
    var amyj = (1)




////创建数组所有值

///Create array with all values



  let users1 = [amya,amyb,amyc,amyd,amye,amyf,amyg,amyh,amyi,amyj]




////最大数量

////Find the max number



 let maxnum = maxElement(users1)




////结果为10

////Result is 10

我的问题是如何在不执行大量if语句的情况下查找结果 10来自哪个变量。

My question is how to find which variable the result "10" came from without doing a massive amount of if statements.

我想要结果是 amyi

I want result to be "amyi"

推荐答案

实际上,我认为问题在于返回变量名而不是值。您可以通过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.

这篇关于Swift-如何从数组中找到最大的值并确定它来自哪个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆