Why is instancetype used?

后端 未结 3 1930
生来不讨喜
生来不讨喜 2020-12-28 15:53

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

- (instancetype) init { 
    self = [super init];         


        
3条回答
  •  梦谈多话
    2020-12-28 16:08

    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.

提交回复
热议问题