Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Find highest value in custom class array with multiple variables

Tags:

arrays

swift

I'd like to find the highest value in my array. I found the method .max() in Apples documentation.

let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
let greatestHeight = heights.max()
print(greatestHeight)
// Prints "Optional(67.5)"

My array has custom datatype. The datatype contains two variables from type integer. How can I find the highest value from one of the variables?

This is my class.

class Example: Codable {

// Variables
var value1: Int
var value2: Int

// Init
init(_value1: Int, _value2: Int) {
    value1 = _value1
    value2 = _value2
}    

}

like image 700
Tobi Avatar asked Nov 04 '18 15:11

Tobi


1 Answers

As you clarified in a comment:

I want to find out the highest value of value1 of all objects in that array

That can be achieved by mapping each object to its value1 and then determining the maximum:

let maxValue1 = examples.map { $0.value1 }.max()

If the given array is really huge then it can be advantageous to use the “lazy variant” to avoid the creation of an intermediate array:

let maxValue1 = examples.lazy.map { $0.value1 }.max()
like image 200
Martin R Avatar answered Nov 15 '22 03:11

Martin R