Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to add a generic type parameter to a protocol?

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).

like image 968
Derek Thurn Avatar asked Feb 02 '16 00:02

Derek Thurn


People also ask

How do you use generics in protocol?

Making a Protocol Generic. There are two ways to create a generic protocol - either by defining an abstract associatedtype or the use of Self (with a capital S). The use of Self or associatedtype is what we like to call "associated types". This is because they are only associated with the protocol they are defined in.

What is a generic type parameter?

Generic Methods A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.

Can a generic class definition can only have one type parameter?

Multiple parametersYou can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.


1 Answers

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.

like image 161
William LeGate Avatar answered Oct 17 '22 05:10

William LeGate