Swift for循环中的模式匹配

时间:2016-08-12 17:04:34

标签: swift pattern-matching

似乎应该有一个" Swiftier"这样做的方式 - 但我仍然围绕着在Swift中进行模式匹配的各种方法。

假设我有一个AnyObject数组,我想循环它,如果该项是Int并且Int是5的倍数,那么我想打印出来。这是我最初的方法:

let myStuff: [AnyObject] = [5, "dog", 11, 15, "cat"]

for item in myStuff {
    if let myInt = item as? Int where myInt % 5 == 0 {
        print ("\(item)")
    }
}

老实说,这还不错......但是使用Swift的所有模式匹配语法,似乎我应该能够将逻辑合并到1行。到目前为止,我还没有找到一种有效的方法 - 但我希望能够做到这样的事情:

//This doesn't work, but I feel like something similar to this should
for item in myStuff where item is Int, item % 5 == 0 {
    print ("\(item)")
}

显然,这不是一件大事 - 但对我来说,理解斯威夫特的模式匹配要好一点,这更像是一种思考练习。

2 个答案:

答案 0 :(得分:9)

您可以将pattern matching conditional castwhere子句结合使用,如下所示:

let myStuff: [AnyObject] = [5, "dog", 11, 15, "cat"]

// item will be an Int, and divisible by 5
for case let item as Int in myStuff where item % 5 == 0 {
    print(item)
}

// Prints:
// 5
// 15

答案 1 :(得分:6)

@Hamish's neat solution是imho,是“最优”的,也是被接受的。但是为了讨论,作为替代方案,可以使用链式功能方法应用稍微相同的逻辑:

let myStuff: [AnyObject] = [5, "dog", 11, 15, "cat"]

myStuff.flatMap{ $0 as? Int }.filter{ $0 % 5 == 0}.forEach {
    print($0)
} /* 5 15 */