Pergunta

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.

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top