ios - 在数组中的对象上使用过滤器来查找最大值? [ swift ]

标签 ios arrays swift filter filtering

我有一堆对象存储在一个数组中。

他们都有属性:

distanceInSeconds: Int

我想知道是否有办法使用过滤器或其他数组方法在数组中的所有对象之间找到此属性的最大值?

例如:

var distances: [Distance] = []
var maxDistance = distances.filter(find max)

最佳答案

这将是 Swifty 方式(通过实现 Comparable):

class Route : Comparable {
    let distance: Int

    init(distance: Int) {
        self.distance = distance
    }
}

func ==(lhs: Route, rhs: Route) -> Bool {
    return lhs.distance == rhs.distance
}

func <(lhs: Route, rhs: Route) -> Bool {
    return lhs.distance < rhs.distance
}

let routes = [
    Route(distance: 4),
    Route(distance: 8),
    Route(distance: 2),
    Route(distance: 7)
]

print(routes.maxElement()?.distance)

输出:

"8"

这适用于 Swift 2。如果您使用的是 Swift 1.2,maxElement(routes) 应该可以工作

关于ios - 在数组中的对象上使用过滤器来查找最大值? [ swift ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31299942/

相关文章:

iphone - "...[UIApplication sharedApplication] openURL..."到底放在哪里?

ios - iOS 应用程序可以在有限的基础上向公众开放吗?

arrays - 如何使用百分比表示法在 ruby​​ 中制作整数数组?

C Malloc 多维字符数组

ios - 使用 NSFetchedResultsController 排序时在多个部分中的一个对象

ios - Swift - 火种效果

iphone - 加载了 nib 文件但未设置 View 导出

javascript - 如何使用jquery生成动态输入并通过id获取值

ios - 代码错误 : linker command failed with exit code 1 googletoolboxmac

ios - 从核心数据和 sqlite 获取最大 ID