Swift 2 - “if”中的模式匹配 [英] Swift 2 - Pattern matching in "if"

查看:96
本文介绍了Swift 2 - “if”中的模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我看到了Apple的WWDC 2015主题演讲。我还查看了一些文档,但是我找不到if if pattern部分,它是如何写在他们展示的幻灯片上的。
(来自 Apple Events 的68分00秒视频)

Recently I've saw the WWDC 2015 keynote from Apple. I also looked at some documentation but I can't find a "pattern matching in if" section, how it was written on one of the slides which they have shown. (68min 00sec video from Apple Events)

你知道这是指什么吗?或者语法?

Do you know what's this refers to? Or the syntax?

推荐答案

它真正意味着if语句现在支持模式匹配,就像已有的switch语句一样。例如,以下现在是使用if / else if / else语句来切换枚举的有效方法。

All it really means is that if statements now support pattern matching like switch statements already have. For example, the following is now a valid way of using if/else if/else statements to "switch" over the cases of an enum.

enum TestEnum {
    case One
    case Two
    case Three
}

let state = TestEnum.Three

if case .One = state {
    print("1")
} else if case .Two = state {
    print("2")
} else {
    print("3")
}

现在可接受以下内容检查 someInteger 是否在给定范围内的方法。

And the following is now an acceptable way of checking if someInteger is within a given range.

let someInteger = 42
if case 0...100 = someInteger {
    // ...
}

以下是使用 Swift编程语言<中的可选模式的更多示例/ a>

Here are a couple more examples using the optional pattern from The Swift Programming Language

let someOptional: Int? = 42
// Match using an enumeration case pattern
if case .Some(let x) = someOptional {
    print(x)
}

// Match using an optional pattern
if case let x? = someOptional {
    print(x)
}

这篇关于Swift 2 - “if”中的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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