Skip to content

Instantly share code, notes, and snippets.

@acalism
Created June 15, 2018 06:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acalism/39ce104cfc69ec0a580f2873a97bf4a2 to your computer and use it in GitHub Desktop.
Save acalism/39ce104cfc69ec0a580f2873a97bf4a2 to your computer and use it in GitHub Desktop.
Implementation and Inheritance of objc lightweight generics
// Header File
NS_ASSUME_NONNULL_BEGIN
// No asterisk after DataType
@interface BaseCell<DataType> : UICollectionViewCell
- (DataType)data;
- (void)bindData:(DataType)data;
@end
// Specify generic type in subclass
@interface MyCell: BaseCell
- (void)bindData:(__kindof UIView *)data;
@end
NS_ASSUME_NONNULL_END
// Implementation File
// Can not use generic type, use `id` instead.
@implementation BaseCell
- (id)data {
return @"no data";
}
- (void)bindData:(id)data {
[NSObject doesNotRecognizeSelector:_cmd];
}
@end
@implementation MyCell
- (void)bindData:(__kindof UIView *)data {
NSLog(@"bindData");
}
@end
// Another file
MyCell *m = [MyCell new];
[m bindData:[UIView new]];
[m bindData:@""]; // Warning: Incompatible pointer types sending
@acalism
Copy link
Author

acalism commented Jun 15, 2018

Further more, generic type can have base class or protocol conforming constraints.
Refer to http://drekka.ghost.io/objective-c-generics/ and https://miqu.me/blog/2015/06/09/adopting-objectivec-generics/

According to Apple's documentation:

Aside from than these Foundation collection classes, Objective-C lightweight generics are ignored by Swift. Any other types using lightweight generics are imported into Swift as if they were unparameterized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment