How to convert Degrees to Radians
Swift Anytime
Posted on January 19, 2023
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
}
Usage:
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
}
}
Usage:
let degrees : Float = 360 // 360 degrees
let radians = degrees.inRadians() // π radians
print(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.
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
November 29, 2024