For-in 循环和类型转换仅适用于匹配类型的对象

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

我看到了答案 here,其中解释了如何告诉编译器数组是循环中的特定类型。

但是,Swift 是否提供了一种方法,使循环仅循环遍历数组中指定类型的项目,而不是崩溃或根本不执行循环?

您可以使用带有大小写模式的 for 循环:

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

这将只为 YourType.

类型(或可转换为)的数组

示例(来自 Loop through subview to check for empty UITextField - Swift):

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

给定一个这样的数组

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

您还可以使用 flatMapforEach 的组合来遍历 Int

things
    .flatMap { [=11=] as? Int }
    .forEach { num in
        print(num)
}

for num in things.flatMap({ [=12=] as? Int }) {
    print(num)
}

在这两种情况下,您都会得到以下输出

// 1
// 4