Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For-in loop and type casting only for objects which match type

I have seen answers here which explain how to tell the compiler that an array is of a certain type in a loop.

However, does Swift give a way so that the loop only loops over items of the specified type in the array rather than crashing or not executing the loop at all?

like image 232
Shuri2060 Avatar asked Aug 07 '16 10:08

Shuri2060


1 Answers

You can use a for-loop with a case-pattern:

for case let item as YourType in array {
    // `item` has the type `YourType` here 
    // ...
}

This will execute the loop body only for those items in the array which are of the type (or can be cast to) YourType.

Example (from Loop through subview to check for empty UITextField - Swift):

for case let textField as UITextField in self.view.subviews {
    if textField.text == "" {
        // ...
    }
}
like image 169
Martin R Avatar answered Sep 29 '22 06:09

Martin R