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

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


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 thearray which are of the type (or can be cast to) YourType.

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

for case let textField as UITextField in self.view.subviews {    if textField.text == "" {        // ...    }}


Given an array like this

let things: [Any] = [1, "Hello", true, "World", 4, false]

you can also use a combination of flatMap and forEach fo iterate through the Int values

things    .flatMap { $0 as? Int }    .forEach { num in        print(num)}

or

for num in things.flatMap({ $0 as? Int }) {    print(num)}

In both cases you get the following output

// 1// 4