This question is inspired by Andrew Carter's comment on a previous question about the new CGSize
initializer in Swift.
The Apple Docs for CGGeometry say:
... your applications should avoid directly reading and writing the data stored in the CGRect data structure. Instead, use the functions described here to manipulate rectangles and to retrieve their characteristics.
Is Apple's recommendation to not directly access the data in a CGRect
still valid with Swift? Why should CGRectGetMidX
, CGRectGetWidth
, etc. be used in place of accessing the values of a CGRect
struct directly, when these properties are now exposed with Swift's new extension on CGRect
?
In Swift 3, it looks like
CGRectGetWidth()
is replaced byCGRect.width
.Consider a non-standard
CGRect
with a negative width and height:This is a valid rectangle according to the Apple docs, as "a rectangle with an origin of
[0.0, 0.0]
and a size of[10.0, 10.0]
is exactly equivalent to a rectangle with an origin of[10.0, 10.0]
and a size of[-10.0, -10.0]
."You can standardize this
CGRect
by calling the legacy inlineCGRectStandardize
method like in Objective-C, or any of the new methods provided on the Swift extension ofCGRect
:But wait! This will reposition your rect on the coordinate plane, not only making your width and height positive, but making your
origin
negative to reflect the initial position of the rect with its negative width and height.The inline
CGRectGet
functions provide an interface to normalize a specific value of your rect, without changing its origin. Swift provides an extension onCGRect
so you can access the normalized values directly, rather than using the legacy C methods provided byCGGeometry
:The new interfaces:
So the answer is yes, the same rules for
CGRect
in Objective-C apply in Swift as well. The only difference here is that Swift provides an extension on someCGGeometry
structs which allow you to move away from the old inline C functions bridged from theCGGeometry
headers.