Szybkimi 5, Arraypodobnie jak inne Sequenceprotokołem w odpowiadające sobie przedmiotów ( Dictionary, Setitp), składa się z dwóch metod zwanych max()i max(by:)ten powrót maksymalna elementów w sekwencji lub niljeśli sekwencja jest pusta.
# 1. Używając Array'smax() metody
Jeżeli typ elementu wewnątrz firmy Przylega do sekwencji Comparableprotokołu (może to być String, Float, Characterlub jeden z niestandardowej klasy lub struktury), będzie w stanie wykorzystać max(), że ma następującą deklarację :
@warn_unqualified_access func max() -> Element?
Zwraca maksymalny element w sekwencji.
Poniższe kody Playground pokazują do użycia max():
let intMax = [12, 15, 6].max()
let stringMax = ["bike", "car", "boat"].max()
print(String(describing: intMax)) // prints: Optional(15)
print(String(describing: stringMax)) // prints: Optional("car")
class Route: Comparable, CustomStringConvertible {
let distance: Int
var description: String { return "Route with distance: \(distance)" }
init(distance: Int) {
self.distance = distance
}
static func ==(lhs: Route, rhs: Route) -> Bool {
return lhs.distance == rhs.distance
}
static func <(lhs: Route, rhs: Route) -> Bool {
return lhs.distance < rhs.distance
}
}
let routes = [
Route(distance: 20),
Route(distance: 30),
Route(distance: 10)
]
let maxRoute = routes.max()
print(String(describing: maxRoute)) // prints: Optional(Route with distance: 30)
# 2. Używając Array'smax(by:) metody
Jeśli typ elementu w twojej sekwencji nie jest zgodny z Comparableprotokołem, będziesz musiał użyć max(by:)tego, który ma następującą deklarację :
@warn_unqualified_access func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> Element?
Zwraca maksymalny element w sekwencji, używając podanego predykatu jako porównania między elementami.
Poniższe kody Playground pokazują do użycia max(by:):
let dictionary = ["Boat" : 15, "Car" : 20, "Bike" : 40]
let keyMaxElement = dictionary.max(by: { (a, b) -> Bool in
return a.key < b.key
})
let valueMaxElement = dictionary.max(by: { (a, b) -> Bool in
return a.value < b.value
})
print(String(describing: keyMaxElement)) // prints: Optional(("Car", 20))
print(String(describing: valueMaxElement)) // prints: Optional(("Bike", 40))
class Route: CustomStringConvertible {
let distance: Int
var description: String { return "Route with distance: \(distance)" }
init(distance: Int) {
self.distance = distance
}
}
let routes = [
Route(distance: 20),
Route(distance: 30),
Route(distance: 10)
]
let maxRoute = routes.max(by: { (a, b) -> Bool in
return a.distance < b.distance
})
print(String(describing: maxRoute)) // prints: Optional(Route with distance: 30)