Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
930 views
in Technique[技术] by (71.8m points)

math - How to get mathemical PI constant in Swift

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.

I also checked the Math package in Darwin and came across the following declaration:

var M_PI: Double { get } /* pi */

So, I assume there is a way to use PI in the code, I just don't know how...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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).

For older versions of Swift:

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

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 is the shortcut (on US-keyboards) that will create the π unicode character.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...