Hai Feng Kao
Hai Feng Kao

Reputation: 5298

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?

Upvotes: 7

Views: 8175

Answers (2)

Douglas Hill
Douglas Hill

Reputation: 1547

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.

Upvotes: 19

Sergii Martynenko Jr
Sergii Martynenko Jr

Reputation: 1407

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

Upvotes: 2

Related Questions