Trying to do arithmetic in a function that returns `CGFloat, I get an error:
Couldn't find overload for '/' that accepts supplied arguments
func kDCControlDegreesToRadians(x : CGFloat) -> CGFloat
{
return (M_PI * (x) / 180.0) // error is here.
}
Has anyone else seen this type of issue?
This is a problem with
double
tofloat
conversion.On a 64-bit machine,
CGFloat
is defined asdouble
and you will compile it without problems becauseM_PI
andx
are both doubles.On a 32-bit machine,
CGFloat
is afloat
butM_PI
is still a double. Unfortunately, there are no implicit casts in Swift, so you have to cast explicitly:The type for
180.0
literal is inferred.In Swift 3
M_PI
is deprecated, useCGFloat.pi
instead:This should fix the error:
The reason the error is occurring is because
x
is explicitly declared to be aCGFloat
, whileM_PI
has the typeCDouble
, as seen in the declaration:Because of this, you need to cast
M_PI
to typeCGFloat
so it matches the type ofx
(as I have done in the code above). This way, there is no conflict in operating on different types.Note that, contrary to what is stated in other answers (and as @Cezar commented), you do not need to explicitly cast
180.0
to theCGFloat
type, because it is a literal, and does not have an explicit type, so will automatically be converted toCGFloat
without needing a manual cast.Its best to abstract away the complexity. First create an extension
then use it in your code such as the following example
At first I was reluctant to extend Double because I don't like creating a custom tailored use of the language (from coding horrors found in C++). However, practical experience has shown this to being a way of abstraction natural to the language.
In this specific case I have a cute trick to recommend
let π = CGFloat(M_PI)
Unicode everywhere, and π is easy to get to with Opt+P