let angle = 45° // angle will be in radians, 45 is in degrees
Compiles under Swift 3. Still keep all values, do all calculations in radians with CGFloats..., but make the code more readable with the constants in degrees. For example: 90°
The ° sign will magically do the degrees to radians conversion.
How to set this up:
Define and use a postfix operator for the ° sign. This operator will do the conversion from degrees to radians.
This example is for Ints, extend these also for the Float types if you have the need.
postfix operator °
protocol IntegerInitializable: ExpressibleByIntegerLiteral {
init (_: Int)
}
extension Int: IntegerInitializable {
postfix public static func °(lhs: Int) -> CGFloat {
return CGFloat(lhs) * .pi / 180
}
}
Some examples of usage:
let angle = 45°
contentView.transform = CGAffineTransform(rotationAngle: 45°)
let angle = 45
contentView.transform = CGAffineTransform(rotationAngle: angle°)
Warning!
It is too easy to use this conversion twice (on a value already in radians by mistake), you will get a very small number as the result, and seemingly the resulting angle will be always zero... DO NOT use ° on the same value twice (do not convert twice)!!:
// OBVIOUSLY WRONG!
let angle = 45°° // ° used twice here
// WRONG! BUT EASY TO MISS
let angle = 45° // ° used here
contentView.transform = CGAffineTransform(rotationAngle: angle°) // ° also used here