xcode 目标 c 中的轻量级泛型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30909722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
lightweight generics in objective c
提问by Hai Feng Kao
I am trying to implement the stack class with the lightweight generic.
But the code failed to compile because Xcode cannot find the definition of ObjectType
我正在尝试使用轻量级泛型实现堆栈类。但是代码编译失败,因为Xcode找不到ObjectType
@implementation Stack
- (ObjectType)popObject !!!!!!!!!Expected a type
{
return self.allObjects.firstObject;
}
@end
It's strange because the header declaration doesn't generate any errors.
这很奇怪,因为标头声明不会产生任何错误。
@interface Stack<__covariant ObjectType> : NSObject
- (ObjectType)popObject;
@property (nonatomic, readonly) NSArray<ObjectType> *allObjects;
@end
I could make it work by changing ObjectType
to id
.
Are there better way to fix the error?
我可以通过更改ObjectType
为id
. 有没有更好的方法来修复错误?
回答by Douglas Hill
Objective-C generics really are lightweight, and were added to improve interoperability with Swift, not to make Objective-C code safer. Similar to nullability, think of generics as a way to annotate your interface rather than a reason to change your implementation.
Objective-C 泛型确实是轻量级的,添加它是为了提高与 Swift 的互操作性,而不是为了使 Objective-C 代码更安全。与可空性类似,将泛型视为注释接口的一种方式,而不是更改实现的理由。
Changing ObjectType
to id
in the implementationis the best way forward.
在实现中更改ObjectType
为是最好的前进方式。id
Further reading: article on Objective C Generics. Read bob's comment on that article if you want to know about __covariant
.
进一步阅读:关于 Objective C 泛型的文章。如果您想了解有关__covariant
.
回答by Sergii Martynenko Jr
Only a presumption, but, if replacing ObjectType
with id
works, maybe you're using not a pointer type?
只有一个假设,但如果更换ObjectType
用id
的作品,也许你正在使用不是指针类型?
I mean, if you have @interface ObjectType
somewhere, than in your Stack
it should be ObjectType*
both in <...>
braces and in method return type
我的意思是,如果你有@interface ObjectType
某个地方,Stack
那么它应该ObjectType*
在<...>
大括号和方法返回类型中
If it's not an issue, sorry for misleading
如果不是问题,抱歉误导