我的阵列:
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返回数组的最大值,而不是索引。您需要找到最大值的索引并将其与其他数组一起使用:
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
}
这是另一种方法:
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)")
}