Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift equivalent for MIN and MAX macros

Tags:

generics

swift

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?

like image 695
mxb Avatar asked Jun 12 '14 14:06

mxb


People also ask

What is MAX () and MIN ()?

Python's built-in min() and max() functions come in handy when you need to find the smallest and largest values in an iterable or in a series of regular arguments.

Can max and min be used for any data type?

MAX and MIN operate on columns that contain character, graphic, numeric, date/time, and binary data (except for binary large object, or BLOB, data). The parentheses are required.

Is Range Max minus Min?

Sometimes it is also useful to use the min and max to calculate the range of a dataset. The range is a numerical indication of the span of our data. To calculate a range, simply subtract the min (13) from the max (110).


1 Answers

min and max are 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 

and used like so:

let min = min(1, 2) let max = max(1, 2) 

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

like image 108
Jack Avatar answered Sep 19 '22 02:09

Jack