Swift Double is Not Convertible to CGFloat

dcbenji picture dcbenji · Aug 5, 2014 · Viewed 26.5k times · Source

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()    
}

Answer

Connor picture Connor · Aug 5, 2014

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()    
    }