是否可以在swift中使用map函数中的模式匹配?

时间:2014-11-11 14:10:14

标签: swift map pattern-matching

例如我有一个数组:

let a = [1, "a", 2.0]

我可以在map函数中使用模式匹配来仅应用整数乘法吗?

在scala中,它看起来像这样:

a map { b => b match {
    case n: Int => n * 2
    case _ => b
}}   

这可以在swift中实现吗?

1 个答案:

答案 0 :(得分:3)

Swift中的模式匹配可以使用switch语句完成:

let a : [Any] = [1, "a", 2.0]
let r = map(a) {
    b -> Any in
    switch b {
    case let n as Int:
        return n * 2
    case let d as Double:
        return d / 2.0
    default:
        return b
    }
}
println(r)
// Output: [2, a, 1.0]