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
}
}
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()
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