Heath Borders
Heath Borders

Reputation: 32117

Objective-C Generics-Safe Array/Dictionary Literal

Are there warnings I can enable to stop assigning array and dictionary literals to variables with generic types that don't match?

// 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,
                                                          };

I created a new iOS project with Xcode Version 7.2 (7C68), and I got no warnings for the above assignments.

I know I could assign create mutable collections and manually assign each value, and get expected warnings:

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'

But I was hoping for something more succinct.

This whole question is more broad than simply calling -\[NSMutableDictionary setObject:forKey:\ which doesn't work.

stringsByString[@2] = @"2";

Upvotes: 2

Views: 1157

Answers (1)

newacct
newacct

Reputation: 122439

No, there is no type inference in Objective-C generics. Hence, array and dictionary literals do not know anything about what context they are used in and must necessarily allow anything as keys and values.

Upvotes: 1

Related Questions