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

前端 未结 1 723
独厮守ぢ
独厮守ぢ 2021-02-19 01:34

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 thi

相关标签:
1条回答
  • 2021-02-19 01:37

    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.

    0 讨论(0)
提交回复
热议问题