Confusion due to Swift lacking implicit conversion of CGFloat

后端 未结 4 639
你的背包
你的背包 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条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 02:51

    Its best to abstract away the complexity. First create an extension

    extension Double {
        /** Converts the specified value in degrees into radians. */
        func degrees() -> CGFloat {
            return CGFloat(self) * CGFloat(M_PI / 180.0)
        }
    }
    

    then use it in your code such as the following example

    let angle = 30.0.degrees()
    let transform = CGAffineTransformRotate(self.sliderControl.transform, angle);
    

    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.

提交回复
热议问题