gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 21:50:38 25 4
gpt4 key购买 nike

我看到了答案here其中解释了如何在循环中告诉编译器数组是某种类型。

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

最佳答案

您可以使用带有 case 模式的 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 == "" {
// ...
}
}

关于swift - For-in 循环和类型转换仅适用于匹配类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38813225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com