Search code examples
xcodeswiftfor-loopfor-in-loop

Specify for in loop type


I would like to specify the type for item in the for in loop below.

for item in items {
}

Currently it is AnyObject but I would like to set it to NSString.


Solution

  • Yes, this is a common problem. The solution is to cast:

    for item in items as [NSString] {
    

    It is perhaps a little surprising that you have to cast the array (items) rather than explicitly declaring the type of the loop variable (item). But that's the syntax, and you'll quickly get used to it.