有什么办法可以将一个泛型类型参数添加到协议中? [英] Is there any way to add a generic type parameter to a protocol?

查看:72
本文介绍了有什么办法可以将一个泛型类型参数添加到协议中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Xcode 7开始,Objective-C为类引入了泛型类型参数。有没有什么方法可以在Objective C协议中使用泛型?我还没有找到一个明显的方法来执行此操作,因为已经为协议使用了等价于 @interface MyClass< ObjectType> (例如 @protocol MyProtocol< ;例如:我想转换这样的代码:



; NSObject>
)。

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

代码如下:

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

常规类可以实现这一点(请参阅NSArray)。

解决方案

如果我正确理解您说的话,您可以:

通过使用:

<$ p $指定该对象应该是的实例或从继承 p> @protocol MYObjectContainer
- (__kindof ObjectType *)objectAtIndex:(NSUInteger)index;
@end

指定集合中的项目 NSArray,NSSet等)应该是ItemType的一个实例(前缀'__kindof'也可以将它扩展为继承自ItemType的对象):

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

请注意,Objective-C泛型被设计用于通过提供编译器来防止隐藏的错误不遵守指定类型时的警告。他们不会 在运行时强制指定的类型。


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

解决方案

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.

这篇关于有什么办法可以将一个泛型类型参数添加到协议中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆