My Array:
let array = [45,12,10,90]
// The number I need in this case is 3
Then I need to grab a value of another array:
let otherArray = [6,6,7,4,0]
I have tried to resolve the problem like this:
let maxPosition = array.max()
let desiredValue = otherArray[maxPosition]
This doesn't seem to work as desired.
Thanks for your help!
The problem there is that max returns the maximum value from your array, not an index. You need to find the index of the maximum value and use it with your other array:
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
}
Another option is to use your collection indices when getting the maximum value:
if let index = array.indices.max(by: { array[$0] < array[$1] }) {
let desiredValue = otherArray[index]
print(desiredValue) // 4
}