17

As of Xcode 7, Objective-C introduced generic type parameters for classes. Is there any way to use generics with Objective C protocols? I haven't found an obvious way to do this because the equivalent to @interface MyClass<ObjectType> is already taken for protocols (e.g. @protocol MyProtocol<NSObject>).

Example: I would like to convert code like this:

@protocol MYObjectContainer
- (id)objectAtIndex:(NSUInteger)index;
@end

to code like this:

@protocol MYObjectContainer
- (ObjectType)objectAtIndex:(NSUInteger)index;
@end

Which is possible with regular classes (see, for example, NSArray).

Derek Thurn
  • 14,953
  • 9
  • 42
  • 64
  • Can you clarify what you are trying to do? Update your question with an example. – rmaddy Feb 02 '16 at 00:52
  • 2
    My guess is that you can't, because generics was added to classes in Objective-C to interface with Swift, and protocols in Swift don't have generics (they have associated types instead). – newacct Feb 03 '16 at 01:31

1 Answers1

5

If I correctly understand what you're saying you can:

Specify that the object should either be either an instance of or inherit from ObjectType by using:

@protocol MYObjectContainer
- (__kindof ObjectType *)objectAtIndex:(NSUInteger)index;
@end

Specify that the items in a collection (NSArray, NSSet, etc.) should be an instance of ItemType (prefix with '__kindof' to also extend this to objects inheriting from ItemType) by using:

@protocol MYObjectContainer
- (CollectionType <ItemType *> *)objectAtIndex:(NSUInteger)index;
@end

Note that Objective-C generics are designed to prevent hidden bugs by providing compiler warnings when a specified type is not adhered to. They do not actually force the specified type at runtime.

William LeGate
  • 540
  • 7
  • 18
  • 1
    Sorry, I do not understand the answer. in the first option, where is ObjectType taken from? there is no such "type" or even pseudo-type. In the second example (inheriting from ItemType) what is "CollectionType" ? and where is "ItemType" defined, or given as template? why would this even compile? – Motti Shneor Mar 11 '19 at 11:12