Math functions

Swift also has a vast range of math functions for you to use when necessary. You never know when you need to pull out some trigonometry, especially when you’re a pro Swift-er and writing those complex games!

Note: Not all of these functions are part of Swift. Some are provided by the operating system. Don’t remove the import statement that comes as part of the playground template or Xcode will tell you it can’t find these functions.

For example, consider the following:

sin(45 * Double.pi / 180)

// 0.7071067811865475

cos(135 * Double.pi / 180)

// -0.7071067811865475

These compute the sine and cosine respectively. Notice how both make use of Double.pi which is a constant Swift provides us, ready-made with pi to as much precision as is possible by the computer. Neat!

Then there’s this:

sqrt(2.0)

// 1.414213562373095

This computes the square root of 2. Did you know that sin(45°) equals 1 over the square root of 2?

Note: Notice how you used 2.0 instead of 2 in the example above? Functions that are provided by the operating systems (like sqrt, sin and cos) are picky and accept only numbers that contain a decimal point.

Not to mention these would be a shame:

max(5, 10)

// 10

min(-5, -10)

// -10

These compute the maximum and minimum of two numbers respectively.

If you’re particularly adventurous you can even combine these functions like so:

max(sqrt(2.0), Double.pi / 2)

// 1.570796326794897

results matching ""

    No results matching ""