【问题标题】:For-in loop and type casting only for objects which match typeFor-in 循环和类型转换仅适用于匹配类型的对象
【发布时间】:2016-12-13 06:50:55
【问题描述】:

我看到了答案here,它解释了如何告诉编译器一个数组是循环中的某种类型。

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

【问题讨论】:

    标签: swift casting for-in-loop


    【解决方案1】:

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

    【讨论】:

    • 谢谢!我希望有这样简单的东西:)
    • 哦 - 而且,如果它是您指定类的子类,它会循环遍历一个项目吗?
    • @QuestionAsker:是的,因为子类的实例总是可以转换为超类的实例。 – 试试吧!
    • 谢谢!最后一件事:我把它改成了字典,所以我现在应该使用:for case (let key as String, let item as YourType) in dictionary {...}?它似乎有效,但我想检查它是否会按我的意图运行
    【解决方案2】:

    给定一个这样的数组

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

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

    things
        .flatMap { $0 as? Int }
        .forEach { num in
            print(num)
    }
    

    for num in things.flatMap({ $0 as? Int }) {
        print(num)
    }
    

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

    // 1
    // 4
    

    【讨论】:

    • flatMap 已弃用,请改用 compactMap (Swift 4)
    猜你喜欢
    • 1970-01-01
    • 2014-11-22
    • 2022-07-30
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    相关资源
    最近更新 更多