generics - type - tuple swift
Swift equivalente para las macros MIN y MAX (5)
En C / Objective-C es posible encontrar el valor mínimo y máximo entre dos números usando las macros MIN y MAX. Swift no admite macros y parece que no hay equivalentes en la biblioteca de idioma / base. ¿Debería ir con una solución personalizada, tal vez basada en genéricos como este?
Como se señaló, Swift proporciona funciones max y min .
Un ejemplo (actualizado para Swift 2.x).
let numbers = [ 1, 42, 5, 21 ]
var maxNumber = Int()
for number in numbers {
maxNumber = max(maxNumber, number as Int)
}
print("the max number is /(maxNumber)") // will be 42
Con Swift, min y max son parte de la Referencia de funciones de la biblioteca estándar Swift .
max(_:_:) tiene la siguiente declaración:
func max<T : Comparable>(_ x: T, _ y: T) -> T
Puedes usarlo así con Int :
let maxInt = max(5, 12) // returns 12
Hay una segunda función llamada max(_:_:_:_:) que le permite comparar aún más parámetros. max(_:_:_:_:) toma un parámetro variable y tiene la siguiente declaración:
func max<T : Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T
Puedes usarlo así con Float :
let maxInt = max(12.0, 18.5, 21, 15, 26, 32.9, 19.1) // returns 32.9
Sin embargo, con Swift, no está limitado a usar max(_:_:) , max(_:_:_:_:) y sus contrapartes Int con Int , Float o Double . De hecho, esas funciones son genéricas y pueden aceptar cualquier tipo de parámetro que se ajuste al protocolo Comparable , ya sea String , Character o una de sus class o struct . De este modo, los siguientes códigos de Playground funcionan perfectamente:
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) // prints "Route with distance: 8"
Además, si desea obtener el elemento máximo de los elementos que están dentro de una Array , un Set , un Dictionary o cualquier otra secuencia, puede utilizar los maxElement() o maxElement(_:) . Consulte esta respuesta de desbordamiento de pila para obtener más detalles.
Prueba esto.
let numbers = [2, 3, 10, 9, 14, 6]
print("Max = /(numbers.maxElement()) Min = /(numbers.minElement())")
min y max ya están definidos en Swift:
func max<T : Comparable>(x: T, y: T, rest: T...) -> T
func min<T : Comparable>(x: T, y: T, rest: T...) -> T
Consulte este excelente informe sobre funciones integradas documentadas e indocumentadas en Swift .
La sintaxis de SWIFT 4 cambió un poco:
public func max<T>(_ x: T, _ y: T) -> T where T : Comparable
public func min<T>(_ x: T, _ y: T) -> T where T : Comparable
y
public func max<T>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T where T : Comparable
public func min<T>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T where T : Comparable
Entonces, cuando lo use, debería escribir como en este ejemplo:
let min = 0
let max = 100
let value = -1000
let currentValue = Swift.min(Swift.max(min, value), max)
Entonces obtienes el valor de 0 a 100, no importa si está por debajo de 0 o más alto 100.