I am trying to implement the stack class with the lightweight generic.
But the code failed to compile because Xcode cannot find the definition of ObjectType
@implementation Stack
- (ObjectType)popObject !!!!!!!!!Expected a type
{
return self.allObjects.firstObject;
}
@end
It's strange because the header declaration doesn't generate any errors.
@interface Stack<__covariant ObjectType> : NSObject
- (ObjectType)popObject;
@property (nonatomic, readonly) NSArray<ObjectType> *allObjects;
@end
I could make it work by changing ObjectType
to id
.
Are there better way to fix the error?
Objective-C generics really are lightweight, and were added to improve interoperability with Swift, not to make Objective-C code safer. Similar to nullability, think of generics as a way to annotate your interface rather than a reason to change your implementation.
Changing ObjectType
to id
in the implementation is the best way forward.
Further reading: article on Objective C Generics. Read bob’s comment on that article if you want to know about __covariant
.