What is difference between auto
and clang type instancetype
?
Where we have to use auto
and where we have to user instancetype
?
In computer programming, an automatic variable is a local variable which is allocated and deallocated automatically when program flow enters and leaves the variable's scope. The scope is the lexical context, particularly the function or block in which a variable is defined.
auto in Objective C is inherited from C and means auto keyword. Defines a local variable as having a local lifetime. Keyword auto uses the following syntax: [auto] data-definition; As the local lifetime is the default for local variables, auto keyword is extremely rarely used.
auto
in Objective C is inherited from C and means auto keyword
Defines a local variable as having a local lifetime.
Keyword auto uses the following syntax:
[auto] data-definition; As the local lifetime is the default for local variables, auto keyword is extremely rarely used.
Note: GNU C extends auto keyword to allow forward declaration of nested functions.
If you are looking for equivalent for C++11's auto
or C#'s var
- in Objective C id
is used.
id a = [NSString new];
id b = [NSNumber new];
But id
is not resolved to concrete type at compile time like auto
in C++11 does.
instancetype
is a contextual keyword that can be used as a result type to signal that a method returns a related result type. For example:
@interface Person
+ (instancetype)personWithName:(NSString *)name;
@end
instancetype, unlike id, can only be used as the result type in a method declaration.
With instancetype, the compiler will correctly infer that the result of +personWithName: is an instance of a Person. And will generate an error if you will try to call
[[Person personWithName:@"Some Name"] methodThatNotExistsInPerson];
If you will use id
compiler will not do so, you will not fix it and will receive runtime error!
Instancetype is used to add a little more "strong typing"to Objective C.
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