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

I get some errors with the following methods:

1) How to return screenHeight / cellCount as CGFLoat for the first method?

2) How to use the equivalent of ObjC 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 } 
+43
ios objective-c swift
Jun 13 '14 at 9:15
source share
4 answers

1: you cannot drag from Int to CGFloat. You must initialize CGFloat with Int as an input.

 return CGFloat(screenHeight) / CGFloat(cellCount) 

2: Use the min and max functions defined by the standard library. They are 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 
+64
Jun 13 '14 at 9:27
source share

If you use Swift 3, max() and min() now called in sequence (i.e. collections) instead of passing in arguments:

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

+5
Mar 15 '17 at 0:03
source share

You need to explicitly convert cellCount to CGFloat , since Swift does not do automatic type conversion between integers and floats:

 return screenHeight / CGFloat(cellCount) 

min and max functions are defined by the standard library.

+3
Jun 13 '14 at 9:26
source share

You can simply use min () and max () - they are built-in.

If you want to flip your own (why? - maybe extend it), you would use something like

 func myMin <T : Comparable> (a: T, b: T) -> T { if a > b { return b } return a } 
+2
Jun 13 '14 at 9:20
source share



All Articles