Swift 3找到阵列中最大的Double的位置

问题描述 投票:0回答:2

我的阵列:

let array = [45,12,10,90]
// The number I need in this case is 3

然后我需要获取另一个数组的值:

let otherArray = [6,6,7,4,0] 

我试图解决这个问题:

let maxPosition = array.max()
let desiredValue = otherArray[maxPosition]

这似乎没有按预期工作。

谢谢你的帮助!

arrays swift3 max ios10
2个回答
2
投票

问题是max返回数组的最大值,而不是索引。您需要找到最大值的索引并将其与其他数组一起使用:

let array = [45,12,10,90]
let otherArray = [6,6,7,4,0]

if let maxValue = array.max(), let index = array.index(of: maxValue) {
    let desiredValue = otherArray[index]
    print(desiredValue)    // 4
}

另一种选择是在获取最大值时使用您的集合索引:

if let index = array.indices.max(by: { array[$0] < array[$1] }) {
    let desiredValue = otherArray[index]
    print(desiredValue)    // 4
}

1
投票

这是另一种方法:

let array = [45,12,10,90]
let otherArray = [6,6,7,4,0]


var maxValueInArray = array[0]
for i in 1..<array.count{
    if array[i] > maxValueInArray{
        maxValueInArray = array[i]
    }
}

if let maxValueIndex = array.index(of: maxValueInArray){
    let desiredValueInOtherArray = otherArray[maxValueIndex]
    print("Maximum value in array is \(maxValueInArray) with index \(maxValueIndex). Value in otherArray under index \(maxValueIndex) is \(desiredValueInOtherArray)")
}
© www.soinside.com 2019 - 2024. All rights reserved.