instancetype should be allowed in argument types

Originator:jonsterling
Number:rdar://10848469 Date Originated:11-Feb-2012
Status:Open Resolved:
Product:Developer Tools Product Version:
Classification:Enhancement Reproducible:N/A
 
Currently, instancetype is a special keyword used to mark a non-inferred related result-type; it only be used in the return-type annotation of a method. It would be more useful if it could be used anywhere within the class interface and implementation (for instance, in method argument types). This would allow much more powerful abstraction and type-safety, without adding full-blown generics to the language; in fact, this would be equivalent to every class having an implicit self-type parameter.

Today, if we were to try to define a Monoid protocol, it would look like the following:

@protocol Monoid
+ (instancetype)identity;
- (instancetype)append:(id)object;
@end

This is statically unsound, however, because the argument of -append: may be anything at all; we are trying to encode, however, a binary operator that takes two arguments of the same type (implicit self, and some other object). If instancetype were allowed to be used in argument type annotations, however, we could be able to encode it more accurately:

@protocol Monoid
+ (instancetype)identity;
- (instancetype)append:(instancetype)object;
@end

@interface Buzz (Monoid) <Monoid>
@end

This is in fact exactly equivalent to a type class in a more powerful language:

class Monoid α where
  identity :: α
  append :: α → α → α

So, in summary: allow instancetype to be used anywhere (rather than just in return type annotations) so that we can achieve greater type safety and cleaner abstraction. For a language that lacks generics, this is essential.

Comments

+1 great feature for objc-c

By ndarmancev at Sept. 19, 2017, 7:45 a.m. (reply...)

+1 Though my feeling is that the real solution would be the introcution of generics. It would be totally awesome.


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!