I saw the syntax below in some example code and am not sure I understand it.
CGRect imageRect = (CGRect){.size = baseImage.size};
Is this simply a shorthand way of initializing a CGRect equivalent to:
CGRect imageRect = CGRectMake(0,0,baseImage.size.width, baseImage.size.height);
Is there any benefit to this syntax aside from slightly less typing?
That’s C99 initializer syntax. You can use it with any structure.
The main advantage to an Objective-C is that it gives you some very Objective-C like syntax, where the fields are close to the values rather than implied by positioning. (That’s not to say this is intentionally similar, or that it’s the only advantage. But it is nice.)
It’s sometimes slightly more typing, but I use it everywhere now.
Consider:
In order to understand this, you need to understand the order of the parameters. You also need to be able to catch the commas easily with your eyes. In this case, that’s pretty easy, but if the expressions were more complicated you’d probably be storing them in a temporary variable first.
The C99 way:
It’s longer, but it’s more explicit. It’s also very easy to follow what is assigned to what, no matter how long the expression are. It’s also more like an Objective-C method. After all, if CGRect was a class, it would probably look like this:
You can also do things like this:
Here, you’re building a rectangle using a
CGPointandCGSize. The compiler understands that.originexpects aCGPoint, and.sizeexpects aCGSize. You’ve provided that. All’s gravy.The equivalent code would be
CGRectMake(myOrigin.x, myOrigin.y, size.width, size.height). By usingCGRectMakeyou’re no longer expressing the same kind of meaning to the compiler. It can’t stop you from assigning part of the size to the origin. It also won’t stop you from assigning the width to the height. It doesn’t even give you a good clue about which is the X and Y; if you’ve used APIs that provide vertical coordinates first, you’ll get it wrong.You can assign part from a structure and part from floats as well:
The
CGRectMakefunction predates C99. I have no evidence to this effect, but I think if C99 had come firstCGRectMakeprobably wouldn’t exist at all; it’s the sort of crusty function you write when your language has no direct way to perform the initialization. But now it does.Basically, if you use it for a while, you’ll probably come to prefer C99 syntax. It’s more explicit, more flexible, more Objective-C-like and harder to screw up.
Unfortunately, as of 4.6 Xcode will not autocomplete structure field names when in the C99 field initializer list.