objective-c - Objective-C 中是否存在强类型集合?

我是 Mac/iPhone 编程和 Objective-C 的新手。在 C# 和 Java 中,我们有“泛型”,即其成员只能是声明类型的集合类。例如,在 C# 中

Dictionary<int, MyCustomObject>

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

最佳答案

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

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 代码中,它们会产生编译器错误:

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

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

@interface GenericsTest<__covariant T> : NSObject

-(void)genericMethod:(T)object;

@end

@implementation GenericsTest

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

@end

Objective-C 的行为与之前的编译器警告相同。

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

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

但 Swift 会完全忽略通用信息。 (在 Swift 3+ 中不再适用。)

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

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.

Interacting with Objective-C APIs

https://stackoverflow.com/questions/848641/

相关文章:

objective-c - NSInvocation 傻瓜?

objective-c - Swift References 中的 _ 下划线代表什么?

objective-c - Objective-C 中可为空、__nullable 和 _Nulla

ios - 较小时 UIScrollView 的中心内容

objective-c - "FOUNDATION_EXPORT"与 "extern"

iphone - 从实例中获取类的名称

ios - 使用 AVFoundation AVPlayer 循环播放视频?

objective-c - 在objective-c中@符号代表什么?

ios - 以编程方式调用电话

iphone - 如何在 Objective-C 2.0 中将方法标记为已弃用?