为什么以下NSDictionary
/NSMutableDictionary
调用会产生错误或警告?为什么通用NSDictionary不会提示有关错误键入的键/赋值?
我期望在这里出现错误,因为rhs NSDictionary
文字不符合012hlhs局部变量的通用类型。
NSDictionary<NSString *, NSNumber *> *foo = @{ @(42) : @"foo" };
我期待在这里的错误,因为密钥类型不匹配NSMutableDictionary
的关键共性类型:
NSMutableDictionary<NSString *, NSNumber *> *foo = [NSMutableDictionary new];
// neither of these calls produces an error. :(
foo[@(42)] = @(42);
[foo setObject:@(42) forKey:@(42)];
我看到一个错误,当我尝试分配不正确类型的值,所以我知道泛型错误有些工作:
NSMutableDictionary<NSString *, NSNumber *> *foo = [NSMutableDictionary new];
foo[@"foo"] = @"bar";
导致以下警告:
Foo.m:81:16: Incompatible pointer types sending 'NSString *' to parameter of type 'NSNumber * _Nullable'
为什么字面赋值或不正确类型的键会导致警告/错误?