How to convert Degrees to Radians in Swift?

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


let degree : Float = 360 // 360 degrees
let radians = degree.radians // 6.28 radians // 2π radians 

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


let degrees : Float = 360 // 360 degrees
let radians = degrees.inRadians() // π radians

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

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.

You've successfully subscribed to Swift Anytime
Great! Next, complete checkout to get full access to all premium content.
Error! Could not sign up. invalid link.
Welcome back! You've successfully signed in.
Error! Could not sign in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Error! Billing info update failed.