如何在Swift中获取数学PI常数 [英] How to get mathemical PI constant in Swift
问题描述
我正在尝试寻找一种方法来在我的Swift代码中包含PI常量.我已经在import Darwin
的另一个答案中找到了帮助,据了解,我可以访问 C函数.
I am trying to find a way to include the PI constant in my Swift code. I already found help in another answer, to import Darwin
which I know gives me access to C functions.
我还检查了Darwin
中的Math
软件包,并遇到了以下声明:
I also checked the Math
package in Darwin
and came across the following declaration:
var M_PI: Double { get } /* pi */
所以,我假设有一种在代码中使用PI的方法,我只是不知道如何 ...
So, I assume there is a way to use PI in the code, I just don't know how...
推荐答案
使用 Swift 3& 4 ,现在pi被定义为浮点数类型Double
,Float
和CGFloat
的静态变量,因此不再需要特定的导入:
With Swift 3 & 4, pi is now defined as a static variable on the floating point number types Double
, Float
and CGFloat
, so no specific imports are required any more:
Double.pi
Float.pi
CGFloat.pi
还要注意,.pi
的实际类型可以由编译器推断.因此,在从上下文中清楚得知您正在使用的情况下,例如CGFloat
,您可以只使用.pi
(感谢@Qbyte和@rickster在注释中指出这一点).
Also note that the actual type of .pi
can be inferred by the compiler. So, in situations where it's clear from the context that you are using e.g. CGFloat
, you can just use .pi
(thanks to @Qbyte and @rickster for pointing that out in the comments).
对于 Swift的较旧版本:
M_PI
最初是在Darwin
中定义的,但也包含在Foundation
和UIKit
中,因此导入其中任何一个都将为您提供正确的访问权限.
M_PI
is originally defined in Darwin
but is also contained in Foundation
and UIKit
, so importing any of these will give you the right access.
import Darwin // or Foundation or UIKit
let pi = M_PI
注意: 如评论中所述,pi也可以在Swift中用作 unicode 字符,因此您也可以这样做
Note: As noted in the comments, pi can also be used as unicode character in Swift, so you might as well do
let π = M_PI
alt + p
是用于创建π
unicode字符的快捷方式(在美国键盘上).
alt + p
is the shortcut (on US-keyboards) that will create the π
unicode character.
这篇关于如何在Swift中获取数学PI常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!