Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Joshua Rapoport
8,415 PointsUsing trig functions in Swift
Apple offers a bunch of functions from a file called 'math.h' containing, you guessed it, math stuff. Among these are trigonometric functions such as sin() and cos().
But, of course, there's a problem when it comes to the tangent function, tan(). It takes in a Double and returns a Double, in radians, but because of a mathematical property to which I am already aware, Swift returns an error if you write tan(M_PI / 2) (M_PI is a constant for pi in the same file), rather than returning nil.
I myself won't program this specifically, but it may be tried by a user of my program. Does anyone know how I could safely wrap this result and present it to the user without crashing my app?
1 Answer
Nathan Tallack
22,164 PointsYour math.h providing your tan function is imported along with Foundation. It is old, from way back in the Darwin days. :)
Consider the following code:
import Foundation
let result = tan(M_PI / 2) // Returns 1.633123935319537e+16
The header shows this:
#include <math.h>
double
tan(double x);
long double
tanl(long double x);
float
tanf(float x);
So in the case of the code above, taking in M_PI as a double returns result as a double.
Perhaps you are needing a long or a float?