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
.
Only a presumption, but, if replacing ObjectType
with id
works, maybe you're using not a pointer type?
I mean, if you have @interface ObjectType
somewhere, than in your Stack
it should be ObjectType*
both in <...>
braces and in method return type
If it's not an issue, sorry for misleading
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