How to convert Degrees to Radians

swiftanytime

Swift Anytime

Posted on January 19, 2023

How to convert Degrees to Radians

When working with rotating view animations or 2d/3d games, you would have to eventually deal with degrees and radians at some point.

Even though, most people have a better understanding of degrees over radians, most of the angles are dealt in radians in Swift [and general math as a matter of fact].
Before diving into the coding path, let’s get the math part clear.

1 pi radian = 180 degrees

Note: pi = 3.14

Thus, for converting degrees to radians, you have to multiply it by pi and divide by 180.

Radians = Degrees * π / 180

Computed Property Extension

One of the easy, clean and efficient way to convert degrees to radians is to extend a computed property to BinaryFloatingPoint which is basically a generic type which includes all the decimal numeric types - Float, Double.

extension BinaryFloatingPoint {
    var radians : Self {
        return self * .pi / 180
   }
Enter fullscreen mode Exit fullscreen mode

Usage:

let degree : Float = 360 // 360 degrees
let radians = degree.radians // 6.28 radians // 2π radians 
Enter fullscreen mode Exit fullscreen mode

Extension Methods

Another convenient way of converting degrees to radians using a method over BinaryFloatingPoint, Double and Float.

extension BinaryFloatingPoint {
    func inRadians() -> Self {
        return self * .pi / 180
    }
}
Enter fullscreen mode Exit fullscreen mode

Usage:

let degrees : Float = 360 // 360 degrees
let radians = degrees.inRadians() // π radians
print(radians)
Enter fullscreen mode Exit fullscreen mode

This above method works for decimal based data types. In the case, the degrees variable is an integer, you can try the following method for converting it to radians.

// prints 6.283185 in console
Enter fullscreen mode Exit fullscreen mode

This works! Congratulations! You have successfully converted degrees to radians.

In a similar way we have an exercise for you, if you are looking forward to convert radians into degrees, then give it a try yourself and share it with us on Twitter @swiftanytime. Till then,

Eat. Sleep. Swift Anytime. Repeat.

💖 💪 🙅 🚩
swiftanytime
Swift Anytime

Posted on January 19, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related