aaronium112
aaronium112

Reputation: 3088

Cannot convert Double to expected argument type CGFloat

How do i convert this function to swift? I'm getting an error I do not understand. You'll need "import QuartzCore" in your class.

Objective C Code

void DrawGridlines(CGContextRef context, CGFloat x, CGFloat width)
{
    for (CGFloat y = -48.5; y <= 48.5; y += 16.0)
    {
        CGContextMoveToPoint(context, x, y);
        CGContextAddLineToPoint(context, x + width, y);
    }
    CGContextSetStrokeColorWithColor(context, graphLineColor());
    CGContextStrokePath(context);
}

Swift Code

func DrawGridLines(context:CGContextRef, x:CGFloat, width:CGFloat)
{
    for var y = -48.5; y <= 48.5; y += 16.0
    {
        CGContextMoveToPoint(context, x, y);
        CGContextAddLineToPoint(context, x + width, y);
    }
    //CGContextSetStrokeColorWithColor(context, graphLineColor());
    //CGContextStrokePath(context);
}

Upvotes: 5

Views: 5463

Answers (2)

Nelu
Nelu

Reputation: 18700

In my case I had to cast the Double value as CGFloat and the error went away.

let newCGFloatVal = cgFloatVal * CGFloat(doubleVal)

Upvotes: 0

vacawama
vacawama

Reputation: 154583

Swift is very strict with variable types. Since you didn't give y a type, Swift inferred that it was a Double.

Variable y needs to be a CGFloat because the function prototype that it is passed to is func CGContextMoveToPoint(c: CGContext?, _ x: CGFloat, _ y: CGFloat). You can declare the type inline in the for statement:

for var y:CGFloat = -48.5; y <= 48.5; y += 16.0

Upvotes: 5

Related Questions