28
votes

I'm trying to draw a simple circle when I get to the following line I get the error "Double is Not Convertable to CGFloat under the startAngle = 0.0

path.addArcWithCenter(center, radius: radius, startAngle: 0.0, endAngle: Float(M_PI) * 2.0, clockwise: true)

How do I "cast" 0.0 to make it CGFloat in Swift?

The complete function I am writing:

func drawCircle() {
    // Drawing code
    var bounds:CGRect = secondView.bounds
    var center = CGPoint()
    center.x = bounds.origin.x + bounds.size.width / 2.0
    center.y = bounds.origin.y + bounds.size.height / 2.0
    var radius = (min(bounds.size.width, bounds.size.height) / 2.0)
    var path:UIBezierPath = UIBezierPath()
    path.addArcWithCenter(center, radius: radius, startAngle: CGFloat(0.0), endAngle: Float(M_PI) * 2.0, clockwise: true)
    path.stroke()    
}
4

4 Answers

29
votes

Convert the values that need to be CGFloat to a CGFloat.

path.addArcWithCenter(center, radius: CGFloat(radius), startAngle: CGFloat(0.0), endAngle: CGFloat(M_PI) * 2.0, clockwise: true)

startAngle probably shouldn't need to be converted though if you're just passing a literal. Also note that this isn't a C style cast, but actually converting between different Swift Types.

Edit: Looking at your whole function, this works.

func drawCircle() {
        // Drawing code
        var bounds:CGRect = self.view.bounds
        var center = CGPoint()
        center.x = bounds.origin.x + bounds.size.width / 2.0
        center.y = bounds.origin.y + bounds.size.height / 2.0
        var radius = (min(bounds.size.width, bounds.size.height) / 2.0)
        var path:UIBezierPath = UIBezierPath()
        path.addArcWithCenter(center, radius: CGFloat(radius), startAngle: CGFloat(0.0), endAngle: CGFloat(Float(M_PI) * 2.0), clockwise: true)
        path.stroke()    
    }
8
votes

You must type cast it via CGFloat(0.0). CGFloat has been adjusted to evaluate differently throughout the beta version of Xcode 6 due to the fact that in Obj-C, CGFloat casts to either a float or a double depending on the target (64 bit versus 32 bit). You must type cast a number to CGFloat in Swift to use a CGFloat as you're never guaranteed to have a float or a double (because this is dependent on the environment). This way, Swift won't throw a fit and will still be 'type' safe.

1
votes

This error will disappear in Swift 5.5.

0
votes

Maybe it's not a good idea, but I used NSNumber to convert Double to Float, then to CGFloat.

let myFloat = NSNumber.init(value: myDouble).floatValue
let myCGFloat = CGFloat(myFloat)