0

I found this code in Objective-c and was wondering what is the equivalent of it in Swift.

CGContextSaveGState(context)
{
    CGContextMoveToPoint(context, self.bounds.size.width, yOffset);
    CGContextAddLineToPoint(context, self.bounds.size.width, yOffset);
    CGContextStrokePath(context);
}
CGContextRestoreGState(context);

What bothers me here are the two braces { }

Nico
  • 6,269
  • 9
  • 45
  • 85

2 Answers2

1

There is no actual need for those braces. This is a coding technique—you can read a post that touches on it here—that makes these start/do something/end blocks a little easier to read, but the code is basically equivalent to:

CGContextSaveGState(context)
CGContextMoveToPoint(context, self.bounds.size.width, yOffset);
CGContextAddLineToPoint(context, self.bounds.size.width, yOffset);
CGContextStrokePath(context);
CGContextRestoreGState(context);

...without the braces. (And that code is exactly the same in Swift as it is in Objective C.)

The only difference is that the braces define a variable scope in your original code, but there's no practical difference in this case.

As far as I can tell, there's no directly equivalent structure in Swift, which doesn't have these "anonymous blocks" (i.e. sections of code within braces, not actual Blocks.) However, you can find some explorations of ways of doing it in this other question.

Community
  • 1
  • 1
Matt Gibson
  • 37,886
  • 9
  • 99
  • 128
-1

The code would be practically the same.
Please, check out Apple's Documentation for further reference:

https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGContext/

Fengson
  • 4,751
  • 8
  • 37
  • 62
  • Thanks for the link but I couldn't find the same kind of example. What bothers me here are the two braces { }. Looks like a block but I'm not sure as I don't really know Objective-c – Nico Mar 11 '15 at 07:56
  • @Nico: It would be useful if you add that information to your question, so that people know what you are actually asking. – Martin R Mar 11 '15 at 08:00