Light generics in lens c
I am trying to implement a lightweight generic stack class. But the code failed to compile because Xcode cannot find the definitionObjectType
@implementation Stack
- (ObjectType)popObject !!!!!!!!!Expected a type
{
return self.allObjects.firstObject;
}
@end
This is weird because the header declaration throws no 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
. Is there a better way to fix the error?
source to share
Objective-C generics are really lightweight and were added to improve interoperability with Swift, not to make Objective-C code more secure. Similar to nullability, think of generics as a way to annotate your interface, not as a reason to change your implementation.
Changing ObjectType
to id
in implementation is the best way forward.
Further reading: An article on Objective C Generics . Read the comments on this article if you want to know about __covariant
.
source to share
Just a presumption, but if the substitution ObjectType
for id
does not work, perhaps you are not using a pointer type?
I mean if you have @interface ObjectType
somewhere than in Stack
, it should be ObjectType*
both in <...>
parentheses and in return type method
If this is not a problem, sorry for the confusion
source to share