OGeek|极客世界-中国程序员成长平台

标题: ios - Objective-C 泛型安全数组/字典字面量 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 15:09
标题: ios - Objective-C 泛型安全数组/字典字面量

是否可以启用警告以停止将数组和字典字面量分配给泛型类型不匹配的变量?

// I expect a warning here.
// I'm assigning an NSArray<NSNumber *> to an NSArray<NSString *>
NSArray<NSString *> *strings = @[@1,
                                 @2,
                                 @3,
                                 ];

// I expect a warning here.
// NSDictionary<NSNumber *, NSNumber *>  to an 
// NSDictionary<NSString *, NSString *> 
NSDictionary<NSString *, NSString *> *stringsByString = @{@1 : @1,
                                                          @2 : @2,
                                                          @3 : @3,
                                                          };

我使用 Xcode 版本 7.2 (7C68) 创建了一个新的 iOS 项目,并且没有收到上述分配的警告。

我知道我可以分配创建可变集合并手动分配每个值,并获得预期的警告:

NSMutableArray<NSString *> *strings = [NSMutableArray new];
[strings addObject1]; 

Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString * _Nonnull'

NSMutableDictionary<NSString *, NSString *> *stringsByString = [NSMutableDictionary new];
stringsByString[@"1"] = @1;

Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString * _Nullable'

但我希望更简洁。

整个问题比简单地调用 -\[NSMutableDictionary setObject:forKey:\ which doesn't work 更广泛。 .

stringsByString[@2] = @"2";



Best Answer-推荐答案


不,Objective-C 泛型中没有类型推断。因此,数组和字典字面量不知道它们在什么上下文中使用,并且必须允许任何东西作为键和值。

关于ios - Objective-C 泛型安全数组/字典字面量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35896636/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4