With Swift, min and max are part of the Swift Standard Reference Functions Reference .
max(_:_:) has the following declaration:
func max<T : Comparable>(_ x: T, _ y: T) -> T
You can use it like this: Int :
let maxInt = max(5, 12)
There is a second function called max(_:_:_:_:) , which allows you to compare even more parameters. max(_:_:_:_:) takes a variational parameter and has the following declaration:
func max<T : Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T
You can use it like this: Float :
let maxInt = max(12.0, 18.5, 21, 15, 26, 32.9, 19.1)
However, with Swift, you are not limited to using max(_:_:) , max(_:_:_:_:) and their min copies with Int , Float or Double . In fact, these functions are generic and can take any type of parameter that conforms to the Comparable protocol, maybe String , Character or one of your custom class or struct . Thus, the following site codes work great:
let maxString = max("Car", "Boat") // returns "Car" (alphabetical order)
class Route: Comparable, CustomStringConvertible { let distance: Int var description: String { return "Route with distance: \(distance)" } 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 route1 = Route(distance: 4) let route2 = Route(distance: 8) let maxRoute = max(route1, route2) print(maxRoute)
In addition, if you want to get the maximum element of elements that is inside Array , a Set , a Dictionary or any other sequence, you can use maxElement () or the maxElement (_ :) methods . See this answer for more details.