Currently I have a tuple array defined as var myArray = [(Date, Double)]()
.
The output of myArray
might look something like this:
[(2016-08-30 07:00:00 +0000, 1.0), (2016-09-30 07:00:00 +0000, 0.050000000000000003),
(2016-10-30 07:00:00 +0000, 20.0), (2017-06-30 07:00:00 +0000, 6.0),
(2017-07-30 07:00:00 +0000, 5.0)]
I am trying to get the max Double
value from the array of tuples but not sure how to go about it.
I see there is a function:
myArray.max { (<#(Date, Double)#>, <#(Date, Double)#>) -> Bool in
}
However, I'm not exactly sure how to use it if that even is the right function to use?
Can someone point me in the right direction?
max
works similar to sort
. You have to pass a comparison $0 < $1
. The result is the (optional) tuple with the maximum value.
if let maxItem = myArray.max(by: {$0.1 < $1.1 }) {
let maxDouble = maxItem.1
}
Once again, you are discouraged from using tuples as a data source
From the documentation:
If your data structure is likely to persist beyond a temporary scope, model it as a class or structure, rather than as a tuple.
You can use the following solution
let max = myArray.max { (left, right) -> Bool in
return left.1 < right.1
}
Or use the $ syntax
myArray.max { $0.1 < $1.1 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With