gpt4 book ai didi

generics - CGFloat:当 Float 时调用 rintf(),当 Double 时调用 rint()

转载 作者:搜寻专家 更新时间:2023-10-31 22:52:41 26 4
gpt4 key购买 nike

当架构是 32 位时,CGFloat 是 Fl​​oat。在这种情况下,我想调用 rintf()

当体系结构为 64 位时,CGFloat 为 Double。在这种情况下,我想调用 rint()

我目前对 Double 进行强制转换,然后调用 rint()

func roundToNearestCell(coordinate: CGFloat) -> CGFloat {
let cellSize = 10.0
return cellSize * CGFloat(rint(Double(coordinate / cellSize)))
}

也许泛型可以很好地处理这两种情况?

最佳答案

这是有效的,尽管必须打开参数类型并提供默认情况是 grody。

func round<T: FloatingPointNumber>(value: T) -> T {
switch value {
case let value as Float:
return rintf(value) as T
case let value as Double:
return rint(value) as T
default:
return 0.0 as T
}
}

当您需要根据传入的项的类型采取不同的操作时,我认为泛型不会很好地工作。在这种情况下,我会使用扩展并让多态性发挥作用:

protocol Roundable {
typealias NumberType
func Round() -> NumberType
}

extension Float: Roundable {
func Round() -> Float {
return rintf(self)
}
}

extension Double: Roundable {
func Round() -> Double {
return rint(self)
}
}

协议(protocol)定义是可选的,但它似乎是 Swiftian。

关于generics - CGFloat:当 Float 时调用 rintf(),当 Double 时调用 rint(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24791734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com