How to find the max value in a Swift object array?
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
Swift 3:
let users = [Usr(15), Usr(25), Usr(20)]
let max = users.map { $0.age }.max()
// max = 25
struct User {
var age: Int
}
let users = [ User(age: 10), User(age: 20), User(age: 30)]
let oldestUser = users.max { $0.age < $1.age }
oldestUser?.age // 30
Use max(by:) function
class Usr {
var age: Int
init(_ age: Int) {
self.age = age
}
}
let users = [Usr(3), Usr(8), Usr(6)]
if let userWithMaxAge : Usr = users.max(by: {$0.age < $1.age}){
print(userWithMaxAge.age)
}
It will print 8