DNB5brims DNB5brims - 7 months ago 100
Swift Question

How to find the max value in a swift object array?

Let say I got an array with

Usr
objects. And the
Usr
object have the attribute
age
. Except from reading the
Usr
object one by one, and compare the
age
value one by one, is there any shortcuts to do so? Thx.

Answer

You can simply map users array to array of user's age and the find max age:

class Usr {
    var age: Int

    init(_ age: Int) {
        self.age = age
    }
}

let users = [Usr(1), Usr(8), Usr(5)]

let maxAge = maxElement(users.map{$0.age}) // 8