Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 385
fulvio Avatar asked Jun 13 '14 09:06

fulvio


3 Answers

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
like image 88
Mick MacCallum Avatar answered Nov 03 '22 19:11

Mick MacCallum


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

like image 10
Alan Zeino Avatar answered Nov 03 '22 19:11

Alan Zeino


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
}
like image 3
Grimxn Avatar answered Nov 03 '22 18:11

Grimxn