Swift equivalent for MIN and MAX macros

mxb picture mxb · Jun 12, 2014 · Viewed 55.3k times · Source

In C / Objective-C it is possible to find the minimum and maximum value between two numbers using MIN and MAX macros. Swift doesn't support macros and it seems that there are no equivalents in the language / base library. Should one go with a custom solution, maybe based on generics like this one?

Answer

Jack picture Jack · Jun 12, 2014

min and max are already defined in Swift:

func max<T : Comparable>(x: T, y: T, rest: T...) -> T
func min<T : Comparable>(x: T, y: T, rest: T...) -> T

See this great writeup on documented & undocumented built-in functions in Swift.