What's the difference between using CGSizeMake

2019-02-10 16:40发布

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?

3条回答
Summer. ? 凉城
2楼-- · 2019-02-10 16:57

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.

查看更多
贪生不怕死
3楼-- · 2019-02-10 17:05

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.

查看更多
Evening l夕情丶
4楼-- · 2019-02-10 17:11

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.

查看更多
登录 后发表回答