Why does swift provide both a CGRect initializer and a CGRectMake function?

When I learned about Core Graphics in swift, in the tutorials I watched on YouTube, instead of CGRect, CGRectMake used to create a CGRect instance.

This is so weird for me. I do not understand why I should use the first, because the parameters are the same, and I think that there is no benefit from using the XXXMake function.

Also, why does swift even have such a “Make” function when CGRect already has an initializer with exactly the same parameters? I think that the developers of the modules use a specific design pattern that I do not know. Did they use them? If yes, what is it? I really want to learn some more design patterns.

+5
source share
1 answer

Short answer: CGRectMake not provided with "Swift". The corresponding C function in the CoreGraphics framework is automatically imported and therefore available in Swift.

Longer answer: CGRectMake is defined in "CGGeometry.h" from the CoreGraphics structure as

 CG_INLINE CGRect CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height) { CGRect rect; rect.origin.x = x; rect.origin.y = y; rect.size.width = width; rect.size.height = height; return rect; } 

In (Objective-) C, this function provides a convenient way to initialize a CGRect variable:

 CGRect r = CGRectMake(x, y, h, w); 

The Swift compiler automatically imports all the functions from the Foundation header files (if they are compatible with Swift), so it is imported as

 public func CGRectMake(x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect 

You can either use this or one of the Swift initializers

 public init(origin: CGPoint, size: CGSize) public init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) public init(x: Double, y: Double, width: Double, height: Double) public init(x: Int, y: Int, width: Int, height: Int) 

I do not think this makes any difference in performance. Many people can use CGRectMake() because they are used to it from the old pre-Swift times. Swift initializers are more "cautious" and more expressive with shortcuts to the explicit argument:

 let rect = CGRect(x: x, y: x, width: w, height: h) 

Update:. Compared to Swift 3 / Xcode 8, CGRectMake no longer available in Swift.

+9
source

Source: https://habr.com/ru/post/1240322/


All Articles