仅适用于匹配类型的对象的for-in循环和类型转换 [英] For-in loop and type casting only for objects which match type

查看:204
本文介绍了仅适用于匹配类型的对象的for-in循环和类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过解答如何告诉编译器的这里

I have seen answers here which explain how to tell the compiler that an array is of a certain type in a loop.

但是,Swift给出一种方式,使得循环只循环数组中指定类型的项目,而不是循环遍历数组中的指定类型的项目。

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?

推荐答案

你可以使用一个case-pattern的for循环:

You can use a for-loop with a case-pattern:

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

这将只为那些项目执行循环体
数组的类型(或可以转换为) YourType

This will execute the loop body only for those items in the array which are of the type (or can be cast to) YourType.

示例来自
通过子视图循环检查对于空的UITextField - Swift ):

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

这篇关于仅适用于匹配类型的对象的for-in循环和类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆