是否可以启用警告以停止将数组和字典文字分配给具有不匹配的泛型类型的变量?
// 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 addObject:@1];
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";
最佳答案
不,Objective-C 泛型中没有类型推断。因此,数组和字典字面量不知道它们在什么上下文中使用,并且必须允许任何东西作为键和值。
关于ios - Objective-C 泛型-安全数组/字典字面量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35896636/