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