Objective-C中有强类型的集合吗? [英] Are there strongly-typed collections in Objective-C?

查看:219
本文介绍了Objective-C中有强类型的集合吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚接触Mac / iPhone编程和Objective-C。在C#和Java中,我们有泛型,集合类的成员只能是声明的类型。例如,在C#

I'm new to Mac/iPhone programming and Objective-C. In C# and Java we have "generics", collection classes whose members can only be of the type declared. For example, in C#

字典< int,MyCustomObject>

只能包含整数的键和MyCustomObject类型的值。是否在Objective-C中存在类似的机制?

can only contain keys that are integers and values that are of type MyCustomObject. Does a similar mechanism exist in Objective-C?

推荐答案

在Xcode 7中,Apple引入了轻量级泛型。在Objective-C中,如果存在类型不匹配,它们将生成编译器警告。

In Xcode 7, Apple has introduced 'Lightweight Generics' to Objective-C. In Objective-C, they will generate compiler warnings if there is a type mismatch.

NSArray<NSString*>* arr = @[@"str"];

NSString* string = [arr objectAtIndex:0];
NSNumber* number = [arr objectAtIndex:0]; // Warning: Incompatible pointer types initializing 'NSNumber *' with an expression of type 'NSString *'

在Swift代码中,它们将产生一个编译器错误:

And in Swift code, they will produce a compiler error:

var str: String = arr[0]
var num: Int = arr[0] //Error 'String' is not convertible to 'Int'

轻量级泛型旨在与NSArray,NSDictionary和NSSet一起使用,但也可以将它们添加到您自己的类中:

Lightweight Generics are intended to be used with NSArray, NSDictionary and NSSet, but you can also add them to your own classes:

@interface GenericsTest<__covariant T> : NSObject

-(void)genericMethod:(T)object;

@end

@implementation GenericsTest

-(void)genericMethod:(id)object {}

@end

Objective-C的行为与之前的编译器警告一样。

Objective-C will behave like it did before with compiler warnings.

GenericsTest<NSString*>* test = [GenericsTest new];

[test genericMethod:@"string"];
[test genericMethod:@1]; // Warning: Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *'

Swift将完全忽略通用信息。

but Swift will ignore the Generic information completely.

var test = GenericsTest<String>() //Error: Cannot specialize non-generic type 'GenericsTest'




除了这些Foundation集合类, Swift忽略了C的轻量级泛型。使用轻量级泛型的任何其他类型都被导入到Swift中,就像它们未被参数化一样。

Aside from than these Foundation collection classes, Objective-C lightweight generics are ignored by Swift. Any other types using lightweight generics are imported into Swift as if they were unparameterized.

与Objective-C API交互

这篇关于Objective-C中有强类型的集合吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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