How to compare two CGSize variables?

Determine whether firstSize fits into secondSize without rotating:

if(firstSize.width <= secondSize.width && firstSize.height <= secondSize.height)

To check for equality you can use, CGSizeEqualToSize function by Apple.

CGSize firstSize = CGSizeMake(1.0,1.0);
CGSize secondSize = CGSizeMake(5.0,3.0);

if(CGSizeEqualToSize(firstSize, secondSize)) {
    //they are equal
}else{
    //they aren't equal
}

This is a great case to use operator overloading.

Compare by area (i.e. is one CGSize larger in size than the other):

func <=(left: CGSize, right: CGSize) -> Bool {
    return (left.width * left.height) <= (right.width * right.height)
}

Or, compare by dimensions (i.e. would one CGSize fit into another):

func <=(left: CGSize, right: CGSize) -> Bool {
    return (left.width <= right.width) && (left.height <= right.height)
}

Obviously you can't include both versions globally in your project, so to be on the safe side you might want to consider making the function private to the current file.


The following function determines if the rectangle of the CGSize in the first parameter fits wholly within or at the extent of the rectangle of the CGSize in the second parameter.

- (BOOL)size:(CGSize)smallerSize isSmallerThanOrEqualToSize:(CGSize)largerSize {

    return CGRectContainsRect(
        CGRectMake(0.0f, 0.0f, largerSize.width, largerSize.height),
        CGRectMake(0.0f, 0.0f, smallerSize.width, smallerSize.height)
    );
}

Instead of writing the full logic yourself with difficult to read conditional statements, you can use the built-in, inline helper functions whose names are descriptive.

While I haven't done the research, this method is probably slower in execution than the accepted answer since it involves converting the two CGSizes to two CGRects C structs. Though it does have the advantage of being quicker to comprehend by the reader.