Skip to Content
The Swift Programming Language

Patterns模式

Match and destructure values.

匹配和解构值。

A pattern represents the structure of a single value or a composite value. For example, the structure of a tuple (1, 2) is a comma-separated list of two elements. Because patterns represent the structure of a value rather than any one particular value, you can match them with a variety of values. For instance, the pattern (x, y) matches the tuple (1, 2) and any other two-element tuple. In addition to matching a pattern with a value, you can extract part or all of a composite value and bind each part to a constant or variable name.

模式代表单个值或者复合值的结构。例如,元组 (1, 2) 的结构是由逗号分隔的,包含两个元素的列表。因为模式代表一种值的结构,而不是特定的某个值,你可以利用模式来匹配各种各样的值。比如,(x, y) 可以匹配元组 (1, 2),以及任何含两个元素的元组。除了利用模式匹配一个值以外,你可以从复合值中提取出部分或全部值,然后分别把各个部分的值和一个常量或变量绑定起来。

In Swift, there are two basic kinds of patterns: those that successfully match any kind of value, and those that may fail to match a specified value at runtime.

Swift 中的模式分为两类:一种能成功匹配任何类型的值,另一种在运行时匹配某个特定值时可能会失败。

The first kind of pattern is used for destructuring values in simple variable, constant, and optional bindings. These include wildcard patterns, identifier patterns, and any value binding or tuple patterns containing them. You can specify a type annotation for these patterns to constrain them to match only values of a certain type.

第一类模式用于解构简单变量、常量和可选绑定中的值。此类模式包括通配符模式、标识符模式,以及包含前两种模式的值绑定模式和元组模式。你可以为这类模式指定一个类型注解,从而限制它们只能匹配某种特定类型的值。

The second kind of pattern is used for full pattern matching, where the values you're trying to match against may not be there at runtime. These include enumeration case patterns, optional patterns, expression patterns, and type-casting patterns. You use these patterns in a case label of a switch statement, a catch clause of a do statement, or in the case condition of an if, while, guard, or for-in statement.

第二类模式用于全模式匹配,这种情况下你试图匹配的值在运行时可能不存在。此类模式包括枚举用例模式、可选模式、表达式模式和类型转换模式。你在 switch 语句的 case 标签中,do 语句的 catch 子句中,或者在 if、while、guard 和 for-in 语句的 case 条件句中使用这类模式。

Grammar of a pattern

  • pattern → wildcard-pattern type-annotation?
  • pattern → identifier-pattern type-annotation?
  • pattern → value-binding-pattern
  • pattern → tuple-pattern type-annotation?
  • pattern → enum-case-pattern
  • pattern → optional-pattern
  • pattern → type-casting-pattern
  • pattern → expression-pattern

Wildcard Pattern 通配符模式

A wildcard pattern matches and ignores any value and consists of an underscore (_). Use a wildcard pattern when you don't care about the values being matched against. For example, the following code iterates through the closed range 1...3, ignoring the current value of the range on each iteration of the loop:

通配符模式由一个下划线(_)构成,用于匹配并忽略任何值。当你想忽略被匹配的值时可以使用该模式。例如,下面这段代码在闭区间 1...3 中迭代,每次迭代都忽略该区间的当前值:

for _ in 1...3 {
    // Do something three times.
}

Grammar of a wildcard pattern

  • wildcard-pattern → _

Identifier Pattern 标识符模式

An identifier pattern matches any value and binds the matched value to a variable or constant name. For example, in the following constant declaration, someValue is an identifier pattern that matches the value 42 of type Int:

标识符模式匹配任何值,并将匹配的值和一个变量或常量绑定起来。例如,在下面的常量声明中,someValue 是一个标识符模式,匹配了 Int 类型的 42:

let someValue = 42

When the match succeeds, the value 42 is bound (assigned) to the constant name someValue.

当匹配成功时,值 42 被绑定(分配)到常量名称 someValue .

When the pattern on the left-hand side of a variable or constant declaration is an identifier pattern, the identifier pattern is implicitly a subpattern of a value-binding pattern.

如果一个变量或常量声明的左边是一个标识符模式,那么这个标识符模式是值绑定模式的子模式。

Grammar of an identifier pattern

  • identifier-pattern → identifier

Value-Binding Pattern 值绑定模式

A value-binding pattern binds matched values to variable or constant names. Value-binding patterns that bind a matched value to the name of a constant begin with the let keyword; those that bind to the name of variable begin with the var keyword.

值绑定模式把匹配到的值绑定给一个变量或常量。把匹配到的值绑定给常量时,用关键字 let,绑定给变量时,用关键字 var。

Identifiers patterns within a value-binding pattern bind new named variables or constants to their matching values. For example, you can decompose the elements of a tuple and bind the value of each element to a corresponding identifier pattern.

在值绑定模式中的标识符模式会把新命名的变量或常量与匹配到的值做绑定。例如,你可以拆开一个元组,然后把每个元素绑定到相应的标识符模式中。

let point = (3, 2)
switch point {
// Bind x and y to the elements of point.
case let (x, y):
    print("The point is at (\(x), \(y)).")
}
// Prints "The point is at (3, 2)."

In the example above, let distributes to each identifier pattern in the tuple pattern (x, y). Because of this behavior, the switch cases case let (x, y): and case (let x, let y): match the same values.

在上面的示例中, let 分配给元组模式(x, y) 中的每个标识符模式。因此, switch 语句中 case let (x, y): 和 case (let x, let y): 的匹配效果是一样的。

Grammar of a value-binding pattern

  • value-binding-pattern → var pattern | let pattern

Tuple Pattern 元组模式

A tuple pattern is a comma-separated list of zero or more patterns, enclosed in parentheses. Tuple patterns match values of corresponding tuple types.

元组模式是由逗号分隔的,具有零个或多个模式的列表,并由一对圆括号括起来。元组模式匹配相应元组类型的值。

You can constrain a tuple pattern to match certain kinds of tuple types by using type annotations. For example, the tuple pattern (x, y): (Int, Int) in the constant declaration let (x, y): (Int, Int) = (1, 2) matches only tuple types in which both elements are of type Int.

你可以使用类型注解去限制一个元组模式能匹配哪种元组类型。例如,在常量声明 let (x, y): (Int, Int) = (1, 2) 中的元组模式 (x, y): (Int, Int) 只匹配两个元素都是 Int 类型的元组。

When a tuple pattern is used as the pattern in a for-in statement or in a variable or constant declaration, it can contain only wildcard patterns, identifier patterns, optional patterns, or other tuple patterns that contain those. For example, the following code isn't valid because the element 0 in the tuple pattern (x, 0) is an expression pattern:

当元组模式用作 for-in 语句或变量或常量声明中的模式时,它只能包含通配符模式、标识符模式、可选模式或包含这些模式的其他元组模式。例如,以下代码无效,因为元组模式 (x, 0) 中的元素 0 是表达式模式:

let points = [(0, 0), (1, 0), (1, 1), (2, 0), (2, 1)]
// This code isn't valid.
for (x, 0) in points {
    /* ... */
}

The parentheses around a tuple pattern that contains a single element have no effect. The pattern matches values of that single element's type. For example, the following are equivalent:

只包含一个元素的元组模式的圆括号没有效果,模式只匹配这个单个元素的类型。举例来说,下面的语句是等效的:

let a = 2        // a: Int = 2
let (a) = 2      // a: Int = 2
let (a): Int = 2 // a: Int = 2

Grammar of a tuple pattern

  • tuple-pattern → ( tuple-pattern-element-list? )
  • tuple-pattern-element-list → tuple-pattern-element | tuple-pattern-element , tuple-pattern-element-list
  • tuple-pattern-element → pattern | identifier : pattern

Enumeration Case Pattern 枚举用例模式

An enumeration case pattern matches a case of an existing enumeration type. Enumeration case patterns appear in switch statement case labels and in the case conditions of if, while, guard, and for-in statements.

枚举用例模式匹配现有的某个枚举类型的某个用例。枚举用例模式出现在 switch 语句中的 case 标签中,以及 if、while、guard 和 for-in 语句的 case 条件中。

If the enumeration case you're trying to match has any associated values, the corresponding enumeration case pattern must specify a tuple pattern that contains one element for each associated value. For an example that uses a switch statement to match enumeration cases containing associated values, see Associated Values.

如果你准备匹配的枚举用例有任何关联的值,则相应的枚举用例模式必须指定一个包含每个关联值元素的元组模式。关于使用 switch 语句来匹配包含关联值的枚举用例的例子,请参阅关联值.

An enumeration case pattern also matches values of that case wrapped in an optional. This simplified syntax lets you omit an optional pattern. Note that, because Optional is implemented as an enumeration, .none and .some can appear in the same switch as the cases of the enumeration type.

枚举用例模式同样会匹配那些被包装成可选值的用例。简化的语法能将可选模式过滤掉。注意,由于 Optional 是枚举实现的,.none 和 .some 都会作为枚举类型的用例出现在 switch 中。

enum SomeEnum { case left, right }
let x: SomeEnum? = .left
switch x {
case .left:
    print("Turn left")
case .right:
    print("Turn right")
case nil:
    print("Keep going straight")
}
// Prints "Turn left".

Grammar of an enumeration case pattern

  • enum-case-pattern → type-identifier? . enum-case-name tuple-pattern?

Optional Pattern 可选模式

An optional pattern matches values wrapped in a some(Wrapped) case of an Optional<Wrapped> enumeration. Optional patterns consist of an identifier pattern followed immediately by a question mark and appear in the same places as enumeration case patterns.

可选模式匹配包装在 Optional<Wrapped> 枚举的 some(Wrapped) 用例中的值。可选模式由一个标识符模式和紧随其后的一个问号组成,可以出现在枚举用例模式能出现的地方。

Because optional patterns are syntactic sugar for Optional enumeration case patterns, the following are equivalent:

由于可选模式是 Optional 和 ImplicitlyUnwrappedOptional 枚举用例模式的语法糖,下面两种写法是等效的:

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)
}

The optional pattern provides a convenient way to iterate over an array of optional values in a for-in statement, executing the body of the loop only for non-nil elements.

可选模式为 for-in 语句提供了一种迭代可选值数组的简便方式,只为数组中非 nil 的元素执行循环体。

let arrayOfOptionalInts: [Int?] = [nil, 2, 3, nil, 5]
// Match only non-nil values.
for case let number? in arrayOfOptionalInts {
    print("Found a \(number)")
}
// Found a 2
// Found a 3
// Found a 5

Grammar of an optional pattern

  • optional-pattern → identifier-pattern ?

Type-Casting Patterns 类型转换模式

There are two type-casting patterns, the is pattern and the as pattern. The is pattern appears only in switch statement case labels. The is and as patterns have the following form:

有两种类型转换模式: is 模式和as 模式。 is 模式仅出现在switch 语句 case 标签中. is 和 as 模式具有以下形式:

is <#type#>
<#pattern#> as <#type#>

The is pattern matches a value if the type of that value at runtime is the same as the type specified in the right-hand side of the is pattern --- or a subclass of that type. The is pattern behaves like the is operator in that they both perform a type cast but discard the returned type.

is 模式仅当一个值的类型在运行时和 is 模式右边的指定类型一致,或者是其子类的情况下,才会匹配这个值。is 模式和 is 运算符有相似表现,它们都进行类型转换,但是 is 模式没有返回类型。

The as pattern matches a value if the type of that value at runtime is the same as the type specified in the right-hand side of the as pattern --- or a subclass of that type. If the match succeeds, the type of the matched value is cast to the pattern specified in the right-hand side of the as pattern.

as 模式仅当一个值的类型在运行时和 as 模式右边的指定类型一致,或者是其子类的情况下,才会匹配这个值。如果匹配成功,被匹配的值的类型被转换成 as 模式右边指定的类型。

For an example that uses a switch statement to match values with is and as patterns, see Type Casting for Any and AnyObject.

关于使用 switch 语句配合 is 模式和 as 模式来匹配值的例子,请参阅Any 和 AnyObject 的类型转换.

Grammar of a type casting pattern

  • type-casting-pattern → is-pattern | as-pattern
  • is-pattern → is type
  • as-pattern → pattern as type

Expression Pattern 表达式模式

An expression pattern represents the value of an expression. Expression patterns appear only in switch statement case labels.

表达式模式代表表达式的值。表达式模式只出现在 switch 语句中的 case 标签中。

The expression represented by the expression pattern is compared with the value of an input expression using the pattern-matching operator (~=) from the Swift standard library. The matches succeeds if the ~= operator returns true. By default, the ~= operator compares two values of the same type using the == operator. It can also match a value with a range of values, by checking whether the value is contained within the range, as the following example shows.

表达式模式代表的表达式会使用 Swift 标准库中的 ~= 运算符与输入表达式的值进行比较。如果 ~= 运算符返回 true,则匹配成功。默认情况下,~= 运算符使用 == 运算符来比较两个相同类型的值。它也可以将一个整型数值与一个 Range 实例中的一段整数区间做匹配,正如下面这个例子所示:

let point = (1, 2)
switch point {
case (0, 0):
    print("(0, 0) is at the origin.")
case (-2...2, -2...2):
    print("(\(point.0), \(point.1)) is near the origin.")
default:
    print("The point is at (\(point.0), \(point.1)).")
}
// Prints "(1, 2) is near the origin."

You can overload the ~= operator to provide custom expression matching behavior. For example, you can rewrite the above example to compare the point expression with a string representations of points.

你可以重载 ~= 运算符来提供自定义的表达式匹配行为。比如你可以重写上面的例子,将 point 表达式与字符串形式表示的点进行比较。

// Overload the ~= operator to match a string with an integer.
func ~= (pattern: String, value: Int) -> Bool {
    return pattern == "\(value)"
}
switch point {
case ("0", "0"):
    print("(0, 0) is at the origin.")
default:
    print("The point is at (\(point.0), \(point.1)).")
}
// Prints "The point is at (1, 2)."

Grammar of an expression pattern

  • expression-pattern → expression

On this page