如何在 Swift 对象数组中找到最大值? [英] How to find the max value in a Swift object array?

查看:33
本文介绍了如何在 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 Usrobject one by one, and compare the age value one by one, is there any shortcuts to do so? Thx.

推荐答案

您可以简单地将 users 数组映射到 user 的年龄数组并查找最大年龄:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆