Type casting in for-in loop

Arbitur picture Arbitur · Sep 27, 2014 · Viewed 33.7k times · Source

I have this for-in loop:

for button in view.subviews {
}

Now I want button to be cast into a custom class so I can use its properties.

I tried this: for button in view.subviews as AClass

But it doesnt work and gives me an error:'AClass' does not conform to protocol 'SequenceType'

And I tried this: for button:AClass in view.subviews

But neither does that work.

Answer

vacawama picture vacawama · Sep 27, 2014

For Swift 2 and later:

Swift 2 adds case patterns to for loops, which makes it even easier and safer to type cast in a for loop:

for case let button as AClass in view.subviews {
    // do something with button
}

Why is this better than what you could do in Swift 1.2 and earlier? Because case patterns allow you to pick your specific type out of the collection. It only matches the type you are looking for, so if your array contains a mixture, you can operate on only a specific type.

For example:

let array: [Any] = [1, 1.2, "Hello", true, [1, 2, 3], "World!"]
for case let str as String in array {
    print(str)
}

Output:

Hello
World!

For Swift 1.2:

In this case, you are casting view.subviews and not button, so you need to downcast it to the array of the type you want:

for button in view.subviews as! [AClass] {
    // do something with button
}

Note: If the underlying array type is not [AClass], this will crash. That is what the ! on as! is telling you. If you're not sure about the type you can use a conditional cast as? along with optional binding if let:

if let subviews = view.subviews as? [AClass] {
    // If we get here, then subviews is of type [AClass]
    for button in subviews {
        // do something with button
    }
}

For Swift 1.1 and earlier:

for button in view.subviews as [AClass] {
    // do something with button
}

Note: This also will crash if the subviews aren't all of type AClass. The safe method listed above also works with earlier versions of Swift.