Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the maximum Double value of a tuple array in Swift?

Tags:

arrays

ios

swift

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?

like image 236
Pangu Avatar asked Jul 31 '17 06:07

Pangu


2 Answers

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.

like image 146
vadian Avatar answered Sep 28 '22 06:09

vadian


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 }
like image 43
Titouan de Bailleul Avatar answered Sep 28 '22 04:09

Titouan de Bailleul