How can I convert from degrees to radians? How can I convert from degrees to radians? ios ios

How can I convert from degrees to radians?


Xcode 11 • Swift 5.1 or later

extension BinaryInteger {    var degreesToRadians: CGFloat { CGFloat(self) * .pi / 180 }}extension FloatingPoint {    var degreesToRadians: Self { self * .pi / 180 }    var radiansToDegrees: Self { self * 180 / .pi }}

Playground

45.degreesToRadians         // 0.7853981633974483Int(45).degreesToRadians    // 0.7853981633974483Int8(45).degreesToRadians   // 0.7853981633974483Int16(45).degreesToRadians  // 0.7853981633974483Int32(45).degreesToRadians  // 0.7853981633974483Int64(45).degreesToRadians  // 0.7853981633974483UInt(45).degreesToRadians   // 0.7853981633974483UInt8(45).degreesToRadians  // 0.7853981633974483UInt16(45).degreesToRadians // 0.7853981633974483UInt32(45).degreesToRadians // 0.7853981633974483UInt64(45).degreesToRadians // 0.7853981633974483Double(45).degreesToRadians    // 0.7853981633974483CGFloat(45).degreesToRadians   // 0.7853981633974483Float(45).degreesToRadians     // 0.7853981Float80(45).degreesToRadians   // 0.78539816339744830963

If you would like to make the binary integer return a floating point type instead of always returning a CGFloat you can make a generic method instead of a computed property:

extension BinaryInteger {    func degreesToRadians<F: FloatingPoint>() -> F {  F(self) * .pi / 180 }}

let radiansDouble: Double = 45.degreesToRadians()   // 0.7853981633974483let radiansCGFloat: CGFloat = 45.degreesToRadians() // 0.7853981633974483let radiansFloat: Float = 45.degreesToRadians()     // 0.7853981let radiansFloat80: Float80 = 45.degreesToRadians() // 0.78539816339744830963


This is not identically what you asked, but in Swift 3 / iOS 10, you can use the Measurement type and do the conversion without knowing the formula!

let result = Measurement(value: 45, unit: UnitAngle.degrees)    .converted(to: .radians).value


Apple provides these GLKit functions for conversion:

func GLKMathDegreesToRadians(_ degrees: Float) -> Floatfunc GLKMathRadiansToDegrees(_ radians: Float) -> Float