According to the clang documentation, a method that returns id
is implicitly known to return instancetype
when it is a class method beginning with new
or alloc
, or an instance method beginning with retain
, autorelease
, init
, or self
.
For the sake of consistency, should these methods also be written to explicitly return instancetype
in new code?
- (instancetype)init {
self = [super init];
if (self) {
// perform initialization
}
return self;
}
Is there any documentation on why or why not, or any reasoning? It seems that in this case it's interpreted exactly the same to the compiler.
It isn't actually necessary because the compiler automatically promotes such methods to returning instancetype
, effectively (as you stated).
This automatic inference is documented in the llvm documentation.
Personally? I always declare them as instancetype
explicitly because it exactly describes the contract and it makes for easier refactoring later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With