如何在Swift对象数组中找到最大值? [英] How to find the max value in a Swift object array?
本文介绍了如何在Swift对象数组中找到最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个包含Usr
对象的数组.并且Usr
对象具有属性age
.除了逐一读取Usr
对象并逐一比较age
值之外,是否有任何捷径可做?谢谢.
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.
推荐答案
您可以简单地将用户数组映射到用户年龄和查找最大年龄数组:
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对象数组中找到最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文