我在Objective-c中找到了这段代码,并想知道在Swift中它的等价物是什么。
CGContextSaveGState(context)
{
CGContextMoveToPoint(context, self.bounds.size.width, yOffset);
CGContextAddLineToPoint(context, self.bounds.size.width, yOffset);
CGContextStrokePath(context);
}
CGContextRestoreGState(context);
这里让我困扰的是这两个花括号{}
发布于 2015-03-11 16:00:48
实际上并不需要这些大括号。这是一种编码技术-you can read a post that touches on it here-that使这些开始/做某事/结束块更容易阅读,但代码基本上等同于:
CGContextSaveGState(context)
CGContextMoveToPoint(context, self.bounds.size.width, yOffset);
CGContextAddLineToPoint(context, self.bounds.size.width, yOffset);
CGContextStrokePath(context);
CGContextRestoreGState(context);
...without大括号。( Swift中的代码与Objective C中的代码完全相同。)
唯一的区别是the braces define a variable scope in your original code,但在这种情况下没有实际的区别。
据我所知,在Swift中没有直接等效的结构,它没有这些“匿名块”(即大括号中的代码段,而不是真正的Blocks)。但是,您可以找到some explorations of ways of doing it in this other question。
发布于 2015-03-11 15:47:01
代码实际上是相同的。
请查看Apple的文档以获得进一步的参考:
https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGContext/
https://stackoverflow.com/questions/28981037
复制相似问题