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

1

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

Uptotheminute answered 2/2, 2016 at 0:50 Comment(2)
Can you clarify what you are trying to do? Update your question with an example.Tantalate
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).Drunken
L
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.

Lyns answered 4/8, 2016 at 2:21 Comment(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?Jemimah

© 2022 - 2024 — McMap. All rights reserved.