Reputation: 792
In Swift, I am trying to use the max() and min() functions.
max<T : Comparable>(x: T, y: T, rest: T...) -> T
min<T : Comparable>(x: T, y: T, rest: T...) -> T
I am trying to use the max() function in this way:
var paddleX: Int = Int(paddle.position.x) + Int(location.x - previousLocation.x)
max(paddleX, paddle.frame.x/2, nil)
but I am getting this error:
Cannot convert the expression's type of '()' to type 'NilType'
Is the nil
causing this problem? What is rest: T...
supposed to be?
Upvotes: 24
Views: 25686
Reputation: 9276
You can use the empty parameters for simple comparable data types, if you have a more complex data structures you need to provide a closure. Note: the order of the comparison are the following for both max
and min
if you do it backward you get wrong results.
[(0, "a"), (2, "b"), (5, "f"), (6, "g")].min(by: {$0.0 < $1.0}) // min (0, "a")
[(0, "a"), (2, "b"), (5, "f"), (6, "g")].max(by: {$0.0 < $1.0}) // max (6, "g")
Upvotes: 0
Reputation: 1108
Don't pass anything at all there. It's a variadic function, you can call it with two or more parameters.
Upvotes: 35