我有一堆存储在数组中的对象。
他们都有财产:
distanceInSeconds: Int
我想知道是否有办法使用过滤器或其他数组方法在数组中的所有对象之间找到此属性的最大值?
例如:
var distances: [Distance] = []
var maxDistance = distances.filter(find max)
答案 0 :(得分:3)
这将是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)
应该可以正常工作
答案 1 :(得分:2)
在Swift 2.0中,minElement和maxElement现在在空序列的情况下返回选项,现在还有版本采用isOrderedBefore闭包。
let maxDistance = distances.maxElement { (a, b) -> Bool in
a.distanceInSeconds < b.distanceInSeconds
}
答案 2 :(得分:1)
我认为你想减少:
设置:
struct Distance {
var distanceInSeconds: Int
}
var distances: [Distance] = []
for _ in 1...10 {
distances += [Distance(distanceInSeconds: Int(arc4random_uniform(100)))]
}
实现:
let max = distances.reduce(distances.first) {
if let left = $0 where left.distanceInSeconds > $1.distanceInSeconds {
return $0
} else {
return $1
}
}
答案 3 :(得分:1)
Comparable
协议使用Swift 4,如果序列中的元素类型符合Comparable
协议,您将能够使用具有以下声明的max()
方法:
func max() -> Self.Element?
返回序列中的最大元素。
用法:的
class Distance: Comparable, CustomStringConvertible {
let distanceInSeconds: Int
var description: String { return "Distance in Int: \(distanceInSeconds)" }
init(distanceInSeconds: Int) {
self.distanceInSeconds = distanceInSeconds
}
static func ==(lhs: Distance, rhs: Distance) -> Bool {
return lhs.distanceInSeconds == rhs.distanceInSeconds
}
static func <(lhs: Distance, rhs: Distance) -> Bool {
return lhs.distanceInSeconds < rhs.distanceInSeconds
}
}
let distances = [
Distance(distanceInSeconds: 20),
Distance(distanceInSeconds: 30),
Distance(distanceInSeconds: 10)
]
let maxDistance = distances.max()
print(String(describing: maxDistance)) // prints: Optional(Distance in Int: 30)
Comparable
协议使用Swift 4,如果序列中的元素类型不符合Comparable
协议,则必须使用具有以下声明的max(by:)
方法:
func max(by areInIncreasingOrder: ((offset: Int, element: Base.Element), (offset: Int, element: Base.Element)) throws -> Bool) rethrows -> (offset: Int, element: Base.Element)?
使用给定的谓词作为元素之间的比较,返回序列中的最大元素。
用法:的
class Distance: CustomStringConvertible {
let distanceInSeconds: Int
var description: String { return "Distance in Int: \(distanceInSeconds)" }
init(distanceInSeconds: Int) {
self.distanceInSeconds = distanceInSeconds
}
}
let distances = [
Distance(distanceInSeconds: 20),
Distance(distanceInSeconds: 30),
Distance(distanceInSeconds: 10)
]
let maxDistance = distances.max (by: { (a, b) -> Bool in
return a.distanceInSeconds < b.distanceInSeconds
})
print(String(describing: maxDistance)) // prints: Optional(Distance in Int: 30)