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

大城市里の小女人 提交于 2019-11-28 04:57:31

问题


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?


回答1:


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 == "" {
        // ...
    }
}



回答2:


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


来源:https://stackoverflow.com/questions/38813225/for-in-loop-and-type-casting-only-for-objects-which-match-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!