ios Swift 中的 MIN() 和 MAX() 并将 Int 转换为 CGFloat

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24201769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:52:46  来源:igfitidea点击:

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

iosobjective-cswift

提问by fulvio

I'm getting some errors with the following methods:

我在使用以下方法时遇到一些错误:

1) How do I return screenHeight / cellCountas a CGFLoatfor the first method?

1)我如何return screenHeight / cellCount作为CGFLoat第一种方法?

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

2) 如何在第二种方法中使用等效的 ObjC 的 MIN() 和 MAX()?

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
}

回答by Mick MacCallum

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

1:你不能从 Int 向下转型到 CGFloat。您必须使用 Int 作为输入初始化 CGFloat。

return CGFloat(screenHeight) / CGFloat(cellCount)

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

2:使用标准库定义的min和max函数。它们的定义如下:

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

回答by Alan Zeino

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

如果您使用的是 Swift 3,max()并且min()现在在序列(即集合)上调用而不是传入参数:

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

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

回答by Greg

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

您需要显式转换cellCountCGFloat,因为 Swift 不会在整数和浮点数之间进行自动类型转换:

return screenHeight / CGFloat(cellCount)

minand maxfunctions are defined by the standard library.

minmax函数由标准库定义。

回答by Grimxn

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

您可以只使用 min() 和 max() - 它们是内置的。

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
}