Swift 3 查找数组中最大Double的位置

Swift 3 Find position of the biggest Double in array

我的阵列:

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]

这似乎没有达到预期效果。

感谢您的帮助!

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

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[[=11=]] < array[] }) {
    let desiredValue = otherArray[index]
    print(desiredValue)    // 4
}

这是另一种方法:

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)")
}