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

前端 未结 1 456
星月不相逢
星月不相逢 2021-01-04 09:25

When I was learning about Core Graphics in swift, the tutorials that I watched on youtube use the CGRectMake function instead of the initializer of CGRect

相关标签:
1条回答
  • 2021-01-04 10:19

    Short answer: CGRectMake is not "provided by 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 framework 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, that function provides a convenient way to initialize a CGRect variable:

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

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

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

    You can either use that one, 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 don't think that it makes any performance difference. Many people might use CGRectMake() because they are used to it from the old pre-Swift times. The Swift initializers are more "swifty" and more expressive with the explicit argument labels:

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

    Update: As of Swift 3/Xcode 8, CGRectMake is no longer available in Swift.

    0 讨论(0)
提交回复
热议问题