2

Is there any compiler option to warn that the type in the for-in loop is wrong?

    NSArray<NSString *> *stringsArray = @[ @"Hello", @"World" ];
    for (UIView *wrongType in stringsArray) {
        NSLog(@"object: %@", wrongType);
    }
Willeke
  • 14,578
  • 4
  • 19
  • 47
ernesto
  • 1,771
  • 2
  • 18
  • 18

1 Answers1

1

Since NSArray may contain objects of multiple classes, there are no way for compiler to detect wrong class in such for loop.

Source - iOS Programming: The Big Nerd Ranch Guide

Sviatoslav
  • 37
  • 7
  • Why couldn't the compiler check? My NSArray is parameterized to `NSString*`. (I know the runtime can't check, because the types are erased.) – ernesto Feb 04 '20 at 16:24
  • I suppose I have no deep enough knowledge to answer why. In your case, if you will add some UIView object to your stringsArray - it will be processed in for loop. Other types will not. – Sviatoslav Feb 05 '20 at 09:27