Why is instancetype used?

Viewed 15045

Can someone please explain to me (in simple terms) why an instancetype is used in Objective-C?

- (instancetype) init { 
    self = [super init];
    if (self) { 
        // Custom initialization
    } 
    return self; 
} 
3 Answers

It is important to use instancetype instead of id in Objective-C if you are also using this code in Swift. Consider the following class declaration:

@interface MyObject : NSObject

+ (id)createMyObject;
- (void)f;

@end

If you want to create a MyObject instance in Swift 5.3 with createMyObject and then call f for this object, you will have to do the following:

let a = MyObject.createMyObject()
(a as? MyObject)?.f()

Now replace id with instancetype in MyObject to have the following Swift code:

let a = MyObject.create()
a?.f()

As you can see now, you can use MyObject.create() instead of MyObject.createMyObject(). And you don't need to use (a as? MyObject) since a is defined as MyObject? and not as Any.

Related