Confusion due to Swift lacking implicit conversion of CGFloat

后端 未结 4 631
你的背包
你的背包 2020-12-16 02:10

Trying to do arithmetic in a function that returns `CGFloat, I get an error:

Couldn\'t find overload for \'/\' that accepts supplied arguments

4条回答
  •  萌比男神i
    2020-12-16 02:43

    This should fix the error:

    func kDCControlDegreesToRadians(x : CGFloat) -> CGFloat
    {
        return (CGFloat(M_PI) * (x) / 180.0)
    }
    

    The reason the error is occurring is because x is explicitly declared to be a CGFloat, while M_PI has the type CDouble, as seen in the declaration:

    var M_PI: CDouble { get } /* pi             */
    

    Because of this, you need to cast M_PI to type CGFloat so it matches the type of x (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 the CGFloat type, because it is a literal, and does not have an explicit type, so will automatically be converted to CGFloat without needing a manual cast.

提交回复
热议问题