How to convert Radians to Degrees in Swift?

swift Aug 16, 2022
How to convert Radians to Degrees 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.

There are rare scenerios where you would have to convert radians to degrees since most of the angles are dealt in radians in Swift. But there is no harm to take a look, right?

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 radians to degrees, you have to multiply it by 180 and divide by pi.

Degrees = Radians * 180 / pi

Computed Property Extension

One of the easy, clean and efficient way to convert radians to degrees 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 degrees : Self {
        return self * 180 / .pi
    }
 }

Usage:

let radians : Double = 2 * .pi // 6.2831...
let degrees = radians.degrees // 360.0 degrees // As a double
let degreesInInt = Int(degrees) // 360 degrees

Extension Methods

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

extension BinaryFloatingPoint {
    func inDegrees() -> Self {
        return self * 180 / .pi 
    }
}

Usage:

let radians : Float = .pi / 2 // half of a pi
let degrees = radians.inDegrees() // 90.0 degrees // in float
let degreesInInt = Int(degrees) // 90 degrees // as an integer

This above method works for decimal based data types. In the case you want degrees to be in integer format, you can convert it to an integer by Int(degrees).

Note on the performance differences of computed property and method:
For methods, the calculations are done everytime the method is called. Moreover, for the computed properties, once the results are computed for a particular value, it is saved and reused throughout. Thus, saving computational power.

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

In a similar way if you are looking forward to convert degrees into radians, check out this article. Moreover, if you are looking forward to apply this to angle, you can check out apple documentation.

Signup now to get notified about our
FREE iOS Workshops!