How to get mathemical PI constant in Swift

拜拜、爱过 提交于 2019-12-17 07:14:28

问题


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


回答1:


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.




回答2:


import Darwin is not needed all M_x are visible with the import Foundation

( Xcode Version 6.4 (6E35b) )




回答3:


warning: 'M_PI' is deprecated: Please use 'Double.pi' or '.pi' to get the value of correct type and avoid casting.

surprisingly, .pi also works fine. M_PI is deprecated as of Swift 4.2.1, Xcode 10.1, which is the current version I am using. SO, Use .pi, or Double.pi



来源:https://stackoverflow.com/questions/26324050/how-to-get-mathemical-pi-constant-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!