由于 Swift 缺少 CGFloat 的隐式转换而造成的混乱 [英] Confusion due to Swift lacking implicit conversion of CGFloat

查看:28
本文介绍了由于 Swift 缺少 CGFloat 的隐式转换而造成的混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在返回 `CGFloat 的函数中进行算术运算,出现错误:

Trying to do arithmetic in a function that returns `CGFloat, I get an error:

找不到接受提供的参数的/"的重载

Couldn't find overload for '/' that accepts supplied arguments

func kDCControlDegreesToRadians(x : CGFloat) -> CGFloat
{ 
     return (M_PI * (x) / 180.0) // error is here. 
}

有没有其他人看到过这种类型的问题?

Has anyone else seen this type of issue?

推荐答案

这是doublefloat转换的问题.

在 64 位机器上,CGFloat 被定义为 double,你编译它不会有问题,因为 M_PIx 都是双打.

On a 64-bit machine, CGFloat is defined as double and you will compile it without problems because M_PI and x are both doubles.

在 32 位机器上,CGFloat 是一个 float,但 M_PI 仍然是一个 double.不幸的是,Swift 中没有隐式强制转换,因此您必须显式强制转换:

On a 32-bit machine, CGFloat is a float but M_PI is still a double. Unfortunately, there are no implicit casts in Swift, so you have to cast explicitly:

return (CGFloat(M_PI) * (x) / 180.0)

推断 180.0 文字的类型.

在 Swift 3 中

M_PI 已弃用,使用 CGFloat.pi 代替:

M_PI is deprecated, use CGFloat.pi instead:

return (x * .pi / 180.0)

这篇关于由于 Swift 缺少 CGFloat 的隐式转换而造成的混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆