如何在 Swift 中获得数学 PI 常数 [英] How to get mathemical PI constant in Swift

查看:23
本文介绍了如何在 Swift 中获得数学 PI 常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种方法来在我的 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...

推荐答案

With Swift 3 &4,pi现在被定义为浮点数类型DoubleFloatCGFloat上的静态变量,所以没有具体的不再需要导入:

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 中定义,但也包含在 FoundationUIKit 中,因此导入任何这些将为您提供正确的访问权限.

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屋!

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