MIN() and MAX() in Swift and converting Int to CGFloat

I'm getting some errors with the following methods:

1) How do I return screenHeight / cellCount as a CGFLoat for the first method?

2) How do I use the equivalent of ObjC's MIN() and MAX() in the second method?

func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
    var cellCount = Int(self.tableView.numberOfRowsInSection(indexPath.section))

    return screenHeight / cellCount as CGFloat
}

// #pragma mark - UIScrollViewDelegate

func scrollViewDidScroll(scrollView: UIScrollView) {
    let height = CGFloat(scrollView.bounds.size.height)
    let position = CGFloat(MAX(scrollView.contentOffset.y, 0.0))

    let percent = CGFloat(MIN(position / height, 1.0))
    blurredImageView.alpha = percent
}

Solution 1:

1: You can't downcast from Int to CGFloat. You have to initialize a CGFloat with the Int as input.

return CGFloat(screenHeight) / CGFloat(cellCount)

2: Use the min and max functions defined by the standard library. They're defined as follows:

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

Usage is as follows.

let lower = min(17, 42) // 17
let upper = max(17, 42) // 42

Solution 2:

If you're using Swift 3, max() and min() are now called on the sequence (i.e., collection) instead of passing in arguments:

let heights = [5, 6] let max = heights.max() // -> 6 let min = heights.min() // -> 5

Solution 3:

You can just use min() and max() - they're built-in.

If you wanted to roll your own (why? - maybe to extend it) you would use something like

func myMin <T : Comparable> (a: T, b: T) -> T {
    if a > b {
        return b
    }
    return a
}

Solution 4:

You need to explicitly convert cellCount to CGFloat, since Swift doesn't do automatic type conversion between integers and floats:

return screenHeight / CGFloat(cellCount)

min and max functions are defined by the standard library.