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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With