【发布时间】:2016-12-13 06:50:55
【问题描述】:
我看到了答案here,它解释了如何告诉编译器一个数组是循环中的某种类型。
但是,Swift 是否提供了一种方法,使循环只循环数组中指定类型的项目,而不是崩溃或根本不执行循环?
【问题讨论】:
标签: swift casting for-in-loop
我看到了答案here,它解释了如何告诉编译器一个数组是循环中的某种类型。
但是,Swift 是否提供了一种方法,使循环只循环数组中指定类型的项目,而不是崩溃或根本不执行循环?
【问题讨论】:
标签: swift casting for-in-loop
您可以使用带有大小写模式的 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 == "" {
// ...
}
}
【讨论】:
for case (let key as String, let item as YourType) in dictionary {...}?它似乎有效,但我想检查它是否会按我的意图运行
给定一个这样的数组
let things: [Any] = [1, "Hello", true, "World", 4, false]
您还可以使用flatMap 和forEach 的组合来遍历Int 值
things
.flatMap { $0 as? Int }
.forEach { num in
print(num)
}
或
for num in things.flatMap({ $0 as? Int }) {
print(num)
}
在这两种情况下,您都会得到以下输出
// 1
// 4
【讨论】: