Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lightweight generics in objective c

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?

like image 576
Hai Feng Kao Avatar asked Jun 18 '15 08:06

Hai Feng Kao


2 Answers

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.

like image 68
Douglas Hill Avatar answered Dec 03 '22 08:12

Douglas Hill


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

like image 25
Sergii Martynenko Jr Avatar answered Dec 03 '22 08:12

Sergii Martynenko Jr