Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type safety in for in loop

I've been experimenting with type safety in objective c for a while now. I think I got some of it, but I am wondering if the following is possible.

NSMutableArray <NSNumber *> *x = [NSMutableArray new];
[x addObject:@14];
[x addObject:@"s"]; // <--- Gives warning, good!

for (NSUInteger i = 0; i < x.count; i++) {
    NSString *s = [x objectAtIndex:i]; // <-- Gives warning, good!
}

NSString *d = x[0]; // <-- Gives warning, good!


//but
for (NSString *s in x) // <-- expected warning but didn't get it
    NSLog(@"%@", [s stringByAppendingString:@"s"]; // <-- no warning just run time error

So my question is can a for in loop give a warning when an incorrect object is used. I want to use the for in since it is fast and hides details of implementation.

like image 859
Haagenti Avatar asked Oct 31 '22 14:10

Haagenti


1 Answers

Here's the issue.

Most of the NSArray/NSMutableArray methods such as addObject: and objectAtIndexedSubscript: (which allows for the modern [index] syntax) take or return ObjectType values. ObjectType is a special indicator that means "use the generic type" specified for the array.

The fast enumeration comes from the NSFastEnumeration protocol and its countByEnumeratingWithState:objects:count: method. Unfortunately, the objects parameter is a C-array of id. It doesn't use ObjectType. Since the objects are type id, the compiler can't do any type checking like it can for the other methods of NSArray.

like image 195
rmaddy Avatar answered Nov 15 '22 08:11

rmaddy