What's the difference between using CGSizeMake and CGSize? Is one better than the other?

孤者浪人 提交于 2019-11-29 21:27:22

问题


CGSize(width: 360, height: 480) and CGSizeMake(360, 480) seem to have the same effect. Is one preferred to the other? What is the difference?


回答1:


The CGSize constructor is a Swift extension on CGSize:

extension CGSize {
    public static var zero: CGSize { get }
    public init(width: Int, height: Int)
    public init(width: Double, height: Double)
}

CGSizeMake is a leftover inline function bridged from Objective-C:

/*** Definitions of inline functions. ***/

// ...

public func CGSizeMake(width: CGFloat, _ height: CGFloat) -> CGSize

Both have the same functionality in Swift, the CGSize constructor is just more "Swifty" than the other and provided as a convenience.




回答2:


While as functionality they don't have any difference, CGSizeMake() is/will be deprecated. It is easier to write and read CGSize(), so Apple prefers you to use CGSize() for the future.




回答3:


So in case if you are talking about the difference on usability aspect then there is no basic difference between CGSize() and CGSizeMake().

But if you are talking about structural and programatic difference between this twos then here is some code snippet structure and explanation as well.

  1. CGSize()

    struct CGSize { var width: CGFloat var height: CGFloat init() init(width width: CGFloat, height height: CGFloat) }
    
  2. CGSizeMake()

    func CGSizeMake(_ width: CGFloat, _ height: CGFloat) -> CGSize
    

Explanation:-

On the first case here i.e. CGSize(), the code clearly demonstrates that its a structure which generally takes height and width as CGFloat()and represent a distance vector but not a physical size. As a vector the value could be negative.

On another hand in case of CGSizeMake(), we can easily understand that its a function rather than a structure. It generally takes height and width as CGFloat()and returns a CGSize() structure.

Example:-

  1. CGSize()

    var sizeValue = CGSize(width: 20, height: 30) //Taking Width and Height
    
  2. CGSizeMake()

    var sizeValue = CGSizeMake(20,30) //Taking Width and Height too but without named parameters
    

Now in case of pure swift usage and code CGSize() is much simpler and understandable than CGSizeMake(). You can get that from the above example right..!!!!

Thanks,

Hope This Helped.



来源:https://stackoverflow.com/questions/34981995/whats-the-difference-between-using-cgsizemake-and-cgsize-is-one-better-than-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!