0

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.

Tom Coomer
  • 6,227
  • 12
  • 45
  • 82

1 Answers1

0

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • And see the discussion of `for ... in` loops in my new Swift tutorial: http://www.apeth.com/swiftBook/ch05.html#_for_loops – matt Jan 19 '15 at 18:25
  • I would just advise you to think twice about casting down to NSString. This is rarely what's wanted. You should probably cast to down to `[String]` instead. – matt Jan 19 '15 at 18:27
  • Use the optional form of the type cast operator (as?) when you are not sure if the downcast will succeed. – ericgu Jan 19 '15 at 18:49