user3674231
user3674231

Reputation:

Objective C Extension equivalent to Swift Extensions?

What would be the equivalent of extensions in Objective-C as in Swift? Is it the same as creating a class function within a class?

 extension CGRect{
        static func rectWithTwoPoints(p1:CGPoint,p2:CGPoint) -> CGRect
        {
            return CGRectMake(min(p1.x, p2.x),min(p1.y, p2.y),fabs(p1.x - p2.x),fabs(p1.y - p2.y));
        }
    }

Upvotes: 3

Views: 2403

Answers (3)

Pushkraj Lanjekar
Pushkraj Lanjekar

Reputation: 2294

In objective C its category and in swift its extension

1.Click File -> New -> File 2.Select Objective-C file under Sources in iOS or Mac OS respectively and Click Next 3.Now select File Type as Category

Select UIView as baseclass of category and set name as "UIView+CGRect"

And you can add your methods like

UIView+CGRect.h of category :

+ (CGRect) rectWithTwoPoints:(CGPoint) p1 andWith:(CGPoint) p2;

UIView+CGRect.m of category :

+ (CGRect) rectWithTwoPoints:(CGPoint) p1 andWith:(CGPoint) p2 {
    return CGRectMake(MIN(p1.x, p2.x), MIN(p1.y, p2.y), fabs(p1.x - p2.x), fabs(p1.y - p2.y));
}

And just import your category in view controller where you want to use it and access like

In ViewController.h

#import "UIView+CGRect.h"

And code will be

CGrect rect = [UIView rectWithTwoPoints:POINT_ONE andWith:rectWithTwoPoints:POINT_TWO];

You will get desired result.

Upvotes: 5

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16660

In Objective-C structures are not similar to classes, but plain C. Therefore they do not have functions associated with them. The usual pattern is that there are (C) functions dealing with the structure. You will find a bunch of them in the headers, for example:

CGRect CGRectMake ( CGFloat x, CGFloat y, CGFloat width, CGFloat height );

If you want to have an extra function, just write it:

CGRect rectWithTwoPoints(CGPoint p1, CGPoint p2)
{
  return CGRectMake(min(p1.x, p2.x),min(p1.y, p2.y),fabs(p1.x - p2.x),fabs(p1.y - p2.y));  
}

And put a prototype into a header, if you want to use it outside the defining compilation unit:

CGRect rectWithTwoPoints(CGPoint p1, CGPoint p2); // <- There is a semicolon for prototyping

Upvotes: 0

Wain
Wain

Reputation: 119031

There is no single equivalent, they're different languages with different capabilities.

For your example the 'equivalent' would be a utility function declared somewhere, likely just in a file, because CGRect isn't a class. It would be a C function, not an Obj-C method.

You could even declare a macro for it.

Upvotes: 1

Related Questions