DNB5brims DNB5brims - 1 year ago 233
Swift Question

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

Let say I got an array with

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download