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

IosObjective CSwift

Ios Problem Overview


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
    

    }

Ios Solutions


Solution 1 - Ios

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 - Ios

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 - Ios

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 - Ios

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfulvioView Question on Stackoverflow
Solution 1 - IosMick MacCallumView Answer on Stackoverflow
Solution 2 - IosAlan ZeinoView Answer on Stackoverflow
Solution 3 - IosGrimxnView Answer on Stackoverflow
Solution 4 - IosGregView Answer on Stackoverflow