Skip to Content
The Swift Programming Language

Types类型

Use built-in named and compound types.

使用内置的命名类型和复合类型。

In Swift, there are two kinds of types: named types and compound types. A named type is a type that can be given a particular name when it's defined. Named types include classes, structures, enumerations, and protocols. For example, instances of a user-defined class named MyClass have the type MyClass. In addition to user-defined named types, the Swift standard library defines many commonly used named types, including those that represent arrays, dictionaries, and optional values.

在 Swift 中,有两种类型:命名类型和复合类型。 命名类型是在定义时可以赋予特定名称的类型。 命名类型包括类、结构体、枚举和协议。 例如,用户定义的名为 MyClass 的类的实例的类型为 MyClass。 除了用户自定义的命名类型,Swift 标准库还定义了许多常用的命名类型,包括表示数组、字典和可选值的类型。

Data types that are normally considered basic or primitive in other languages --- such as types that represent numbers, characters, and strings --- are actually named types, defined and implemented in the Swift standard library using structures. Because they're named types, you can extend their behavior to suit the needs of your program, using an extension declaration, discussed in Extensions and Extension Declaration.

在很多编程语言中通常被认为是基本或原始的数据类型——例如表示数字、字符和字符串的类型——实际上是使用结构体在 Swift 标准库中定义和实现的命名类型。 因为这些基本数据类型是命名类型,所以你可以使用扩展声明(在扩展和扩展声明中讨论)来扩展它们的行为,以满足你程序的需求。

A compound type is a type without a name, defined in the Swift language itself. There are two compound types: function types and tuple types. A compound type may contain named types and other compound types. For example, the tuple type (Int, (Int, Int)) contains two elements: The first is the named type Int, and the second is another compound type (Int, Int).

复合类型指的是在 Swift 语言本身中定义的没有名称的类型。有两种复合类型:函数类型和元组类型。 复合类型可能包含命名类型和其他复合类型。 例如,元组类型 (Int, (Int, Int)) 包含两个元素:第一个是命名类型 Int,第二个是另一个复合类型 (Int, Int)。

You can put parentheses around a named type or a compound type. However, adding parentheses around a type doesn't have any effect. For example, (Int) is equivalent to Int.

你可以在命名类型或复合类型周围加上括号。 但是,在类型周围添加括号不会产生任何影响。 例如,(Int) 等同于 Int。

This chapter discusses the types defined in the Swift language itself and describes the type inference behavior of Swift.

本章讨论了 Swift 语言本身定义的类型,并描述了 Swift 的类型推断行为。

Grammar of a type

  • type → function-type
  • type → array-type
  • type → dictionary-type
  • type → type-identifier
  • type → tuple-type
  • type → optional-type
  • type → implicitly-unwrapped-optional-type
  • type → protocol-composition-type
  • type → opaque-type
  • type → boxed-protocol-type
  • type → metatype-type
  • type → any-type
  • type → self-type
  • type → ( type )

Type Annotation 类型注解

A type annotation explicitly specifies the type of a variable or expression. Type annotations begin with a colon (:) and end with a type, as the following examples show:

类型注解显式指定变量或表达式的类型。 类型注解以冒号 (:) 开头,以类型结尾,如下例所示:

let someTuple: (Double, Double) = (3.14159, 2.71828)
func someFunction(a: Int) { /* ... */ }

In the first example, the expression someTuple is specified to have the tuple type (Double, Double). In the second example, the parameter a to the function someFunction is specified to have the type Int.

在第一个示例中,表达式 someTuple 被指定为元组类型 (Double, Double)。 在第二个示例中,函数 someFunction 的参数 a 被指定为类型 Int。

Type annotations can contain an optional list of type attributes before the type.

类型注解可以在类型之前包含一个可选的类型属性列表。

Grammar of a type annotation

  • type-annotation → : attributes? type

Type Identifier 类型标识符

A type identifier refers to either a named type or a type alias of a named or compound type.

类型标识符指的是命名类型,或命名类型、复合类型的类型别名。

Most of the time, a type identifier directly refers to a named type with the same name as the identifier. For example, Int is a type identifier that directly refers to the named type Int, and the type identifier Dictionary<String, Int> directly refers to the named type Dictionary<String, Int>.

大多数情况下,类型标识符直接指的是与标识符同名的命名类型。 例如,Int 是一个类型标识符,直接指的是命名类型 Int,类型标识符 Dictionary<String, Int> 直接指的是命名类型 Dictionary<String, Int>。

There are two cases in which a type identifier doesn't refer to a type with the same name. In the first case, a type identifier refers to a type alias of a named or compound type. For instance, in the example below, the use of Point in the type annotation refers to the tuple type (Int, Int).

有两种情况,类型标识符不是指与其同名的类型。 第一种情况,类型标识符指的是命名类型或复合类型的类型别名。 例如,在下面的示例中,类型注解中使用的 Point 指的是元组类型 (Int, Int)。

typealias Point = (Int, Int)
let origin: Point = (0, 0)

In the second case, a type identifier uses dot (.) syntax to refer to named types declared in other modules or nested within other types. For example, the type identifier in the following code references the named type MyType that's declared in the ExampleModule module.

第二种情况,类型标识符使用点(.)语法来引用声明在其他模块中或嵌套在其他类型中的命名类型。例如,以下代码中的类型标识符引用了在 ExampleModule 模块中声明的命名类型 MyType。

var someValue: ExampleModule.MyType

Grammar of a type identifier

  • type-identifier → type-name generic-argument-clause? | type-name generic-argument-clause? . type-identifier
  • type-name → identifier

Tuple Type 元组类型

A tuple type is a comma-separated list of types, enclosed in parentheses.

元组类型是由圆括号括起来的、以逗号分隔的类型列表。

You can use a tuple type as the return type of a function to enable the function to return a single tuple containing multiple values. You can also name the elements of a tuple type and use those names to refer to the values of the individual elements. An element name consists of an identifier followed immediately by a colon (:). For an example that demonstrates both of these features, see Functions with Multiple Return Values.

你可以将元组类型用作函数的返回类型,使函数能够返回一个包含多个值的元组。你还可以为元组类型的元素命名,并使用这些名称来引用各个元素的值。元素名称由一个标识符紧跟一个冒号(:)组成。有关演示这两个特性的示例,请参阅 多重返回值函数。

When an element of a tuple type has a name, that name is part of the type.

当元组类型的某个元素有名称时,该名称是类型的一部分。

var someTuple = (top: 10, bottom: 12)  // someTuple is of type (top: Int, bottom: Int)
someTuple = (top: 4, bottom: 42) // OK: Names match.
someTuple = (9, 99)              // OK: Names are inferred.
someTuple = (left: 5, right: 5)  // Error: Names don't match.

All tuple types contain two or more types, except for Void which is a type alias for the empty tuple type, ().

除了 Void 是空元组类型 () 的类型别名外,所有元组类型都包含两个或更多类型。

Grammar of a tuple type

  • tuple-type → ( ) | ( tuple-type-element , tuple-type-element-list )
  • tuple-type-element-list → tuple-type-element | tuple-type-element , tuple-type-element-list
  • tuple-type-element → element-name type-annotation | type
  • element-name → identifier

Function Type 函数类型

A function type represents the type of a function, method, or closure and consists of a parameter and return type separated by an arrow (->):

函数类型表示函数、方法或闭包的类型,由参数类型和返回类型组成,二者用箭头(->)分隔:

(<#parameter type#>) -> <#return type#>

The parameter type is comma-separated list of types. Because the return type can be a tuple type, function types support functions and methods that return multiple values.

参数类型是一个用逗号分隔的类型列表。由于返回类型可以是元组类型,函数类型支持返回多个值的函数和方法。

A parameter of the function type () -> T (where T is any type) can apply the autoclosure attribute to implicitly create a closure at its call sites. This provides a syntactically convenient way to defer the evaluation of an expression without needing to write an explicit closure when you call the function. For an example of an autoclosure function type parameter, see Autoclosures.

函数类型 () -> T(其中 T 是任意类型)的形参可以应用 autoclosure 特性,在调用处隐式创建闭包。这提供了一种语法上方便的方式,在调用函数时延迟表达式的求值,而无需编写显式闭包。有关自动闭包函数类型形参的示例,请参阅 自动闭包。

A function type can have variadic parameters in its parameter type. Syntactically, a variadic parameter consists of a base type name followed immediately by three dots (...), as in Int.... A variadic parameter is treated as an array that contains elements of the base type name. For instance, the variadic parameter Int... is treated as [Int]. For an example that uses a variadic parameter, see Variadic Parameters.

函数类型可以在其参数类型中包含可变参数。在语法上,可变参数由一个基础类型名紧跟三个点(...)组成,如 Int...。可变参数被视为包含该基础类型元素的数组。例如,可变参数 Int... 被视为 [Int]。有关使用可变参数的示例,请参阅 可变参数。

To specify an in-out parameter, prefix the parameter type with the inout keyword. You can't mark a variadic parameter or a return type with the inout keyword. In-out parameters are discussed in In-Out Parameters.

要指定一个输入输出参数,需要在参数类型前加上 inout 关键字。你不能在可变参数或返回类型上使用 inout 关键字。输入输出参数在 输入输出参数 中有讨论。

If a function type has only one parameter and that parameter's type is a tuple type, then the tuple type must be parenthesized when writing the function's type. For example, ((Int, Int)) -> Void is the type of a function that takes a single parameter of the tuple type (Int, Int) and doesn't return any value. In contrast, without parentheses, (Int, Int) -> Void is the type of a function that takes two Int parameters and doesn't return any value. Likewise, because Void is a type alias for (), the function type (Void) -> Void is the same as (()) -> () --- a function that takes a single argument that's an empty tuple. These types aren't the same as () -> () --- a function that takes no arguments.

如果函数类型只有一个参数,且参数类型为元组,则在写该函数类型时必须给元组加括号。例如,((Int, Int)) -> Void 是一个接受单个参数的函数类型,该参数的类型为 (Int, Int),并且不返回任何值。相反,如果不加括号,(Int, Int) -> Void 是一个接受两个 Int 参数并且不返回任何值的函数类型。同样,因为 Void 是 () 的类型别名,所以函数类型 (Void) -> Void 与 (()) -> () 相同 --- 一个接受单个参数为空元组的函数。这些类型与 () -> () 不同 --- 一个不接受任何参数的函数。

Argument names in functions and methods aren't part of the corresponding function type. For example:

函数和方法中的参数名不是相应函数类型的一部分。例如:

func someFunction(left: Int, right: Int) {}
func anotherFunction(left: Int, right: Int) {}
func functionWithDifferentLabels(top: Int, bottom: Int) {}

var f = someFunction // The type of f is (Int, Int) -> Void, not (left: Int, right: Int) -> Void.
f = anotherFunction              // OK
f = functionWithDifferentLabels  // OK

func functionWithDifferentArgumentTypes(left: Int, right: String) {}
f = functionWithDifferentArgumentTypes     // Error

func functionWithDifferentNumberOfArguments(left: Int, right: Int, top: Int) {}
f = functionWithDifferentNumberOfArguments // Error

Because argument labels aren't part of a function's type, you omit them when writing a function type.

因为参数标签不是函数类型的一部分,所以在写函数类型时要省略它们。

var operation: (lhs: Int, rhs: Int) -> Int     // Error
var operation: (_ lhs: Int, _ rhs: Int) -> Int // OK
var operation: (Int, Int) -> Int               // OK

If a function type includes more than a single arrow (->), the function types are grouped from right to left. For example, the function type (Int) -> (Int) -> Int is understood as (Int) -> ((Int) -> Int) --- that is, a function that takes an Int and returns another function that takes and returns an Int.

如果一个函数类型包含多个箭头(->)时,表示该函数类型实际上是一个高阶函数,它接受一些参数并返回另一个函数。在这种情况下,函数类型是从右向左进行分组的。例如,函数类型(Int) -> (Int) -> Int被理解为(Int) -> ((Int) -> Int) --- 即一个接受Int参数并返回另一个接受Int参数并返回Int结果的函数。

Function types for functions that can throw or rethrow an error must include the throws keyword. You can include a type after throws in parentheses to specify the type of error that the function throws. The throw error type must conform to the Error protocol. Writing throws without specifying a type is the same as writing throws(any Error). Omitting throws is the same as writing throws(Never). The error type that a function throws can be any type that conforms to Error, including generic types, boxed protocol types, and opaque types.

可能抛出或重新抛出错误的函数类型必须包含throws关键字。你可以在throws后面加上括号中的类型来指定函数抛出的错误类型。抛出的错误类型必须符合Error协议。写throws而不指定类型等同于写throws(any Error)。省略throws等同于写throws(Never)。函数抛出的错误类型可以是任何符合Error协议的类型,包括泛型类型、封装协议类型和不透明类型。

The type of error that a function throws is part of that function's type, and a subtype relationship between error types means the corresponding function types are also subtypes. For example, if you declare a custom MyError type, the relationship between some function types is as follows, from supertype to subtype:

函数抛出的错误类型是该函数类型的一部分,错误类型之间的子类型关系意味着相应的函数类型也是子类型关系。例如,如果你声明了一个自定义的MyError类型,一些函数类型之间的关系如下,从超类型到子类型:

  1. Functions that throw any error, marked throws(any Error)
  2. Functions that throw a specific error, marked throws(MyError)
  3. Functions that don't throw, marked throws(Never)
  1. 抛出任何错误的函数,标记为throws(any Error)
  2. 抛出特定错误的函数,标记为throws(MyError)
  3. 不抛出错误的函数,标记为throws(Never)

As a result of these subtype relationships:

由于这些子类型关系:

  • You can use a nonthrowing function in the same places as a throwing function.
  • You can use a function that throws a concrete error type in the same places as a throwing function.
  • You can use a function that throws a more specific error type in the same places as a function that throws a more general error type.
  • 你可以在需要抛出函数的地方使用不抛出函数。
  • 你可以在需要抛出函数的地方使用抛出具体错误类型的函数。
  • 你可以在需要抛出更一般错误类型的函数的地方使用抛出更特定错误类型的函数。

If you use an associated type or a generic type parameter as the thrown error type in a function type, then that associated type or generic type parameter is implicitly required to conform to the Error protocol.

如果使用关联类型或泛型类型参数指定抛出的错误类型,那么该关联类型或泛型类型参数隐式地需要符合Error协议。

Throwing and rethrowing functions are described in Throwing Functions and Methods and Rethrowing Functions and Methods.

抛出函数和重抛函数在 抛出函数和方法 和 再抛出函数和方法 中有介绍。

Function types for asynchronous functions must be marked with the async keyword. The async keyword is part of a function's type, and synchronous functions are subtypes of asynchronous functions. As a result, you can use a synchronous function in the same places as an asynchronous one. For information about asynchronous functions, see Asynchronous Functions and Methods.

异步函数的函数类型必须用 async 关键字标记。async 关键字是函数类型的一部分,同步函数是异步函数的子类型。因此,你可以在任何可以使用异步函数的地方使用同步函数。有关异步函数的信息,请参阅 异步函数和方法。

Restrictions for Nonescaping Closures 非逃逸闭包的限制

A parameter that's a nonescaping function can't be stored in a property, variable, or constant of type Any, because that might allow the value to escape.

作为非逃逸函数的形参不能存储在 Any 类型的属性、变量或常量中,因为这可能会让值发生逃逸。

A parameter that's a nonescaping function can't be passed as an argument to another nonescaping function parameter. This restriction helps Swift perform more of its checks for conflicting access to memory at compile time instead of at runtime. For example:

一个非逃逸函数不能作为另一个非逃逸函数的参数传入。这个限制有助于 Swift 在编译时而不是运行时执行更多对内存访问冲突的检查。例如:

let external: (() -> Void) -> Void = { _ in () }
func takesTwoFunctions(first: (() -> Void) -> Void, second: (() -> Void) -> Void) {
    first { first {} }       // Error
    second { second {}  }    // Error

    first { second {} }      // Error
    second { first {} }      // Error

    first { external {} }    // OK
    external { first {} }    // OK
}

In the code above, both of the parameters to takesTwoFunctions(first:second:) are functions. Neither parameter is marked @escaping, so they're both nonescaping as a result.

在上述代码中,takesTwoFunctions(first:second:) 的两个参数都是函数。由于它们都没有标记为 @escaping,因此它们都是非逃逸的。

The four function calls marked "Error" in the example above cause compiler errors. Because the first and second parameters are nonescaping functions, they can't be passed as arguments to another nonescaping function parameter. In contrast, the two function calls marked "OK" don't cause a compiler error. These function calls don't violate the restriction because external isn't one of the parameters of takesTwoFunctions(first:second:).

上述代码中标记为"错误"的四个函数调用会导致编译器错误。因为 first 和 second 参数是非逃逸函数,所以它们不能被传递给另一个非逃逸函数参数。另一方面,标记为"正确"的两个函数调用不会导致编译器错误。这些函数调用没有违反限制,因为 external 不是 takesTwoFunctions(first:second:) 的参数之一。

If you need to avoid this restriction, mark one of the parameters as escaping, or temporarily convert one of the nonescaping function parameters to an escaping function by using the withoutActuallyEscaping(_:do:) function. For information about avoiding conflicting access to memory, see Memory Safety.

如果你需要避免这个限制,可以将其中一个参数标记为逃逸的,或者使用 withoutActuallyEscaping(_:do:) 函数临时将其中一个非逃逸函数参数转换为逃逸函数。有关避免内存访问冲突的信息,请参阅 内存安全。

Grammar of a function type

  • function-type → attributes? function-type-argument-clause async? throws-clause? -> type
  • function-type-argument-clause → ( )
  • function-type-argument-clause → ( function-type-argument-list ...? )
  • function-type-argument-list → function-type-argument | function-type-argument , function-type-argument-list
  • function-type-argument → attributes? parameter-modifier? type | argument-label type-annotation
  • argument-label → identifier
  • throws-clause → throws | throws ( type )

Array Type 数组类型

The Swift language provides the following syntactic sugar for the Swift standard library Array<Element> type:

Swift 语言为 Swift 标准库 Array<Element> 类型提供了以下语法糖:

[<#type#>]

In other words, the following two declarations are equivalent:

换句话说,以下两个声明是等价的:

let someArray: Array<String> = ["Alex", "Brian", "Dave"]
let someArray: [String] = ["Alex", "Brian", "Dave"]

In both cases, the constant someArray is declared as an array of strings. The elements of an array can be accessed through subscripting by specifying a valid index value in square brackets: someArray[0] refers to the element at index 0, "Alex".

在这两种情况下,常量 someArray 都被声明为一个字符串数组。可以通过使用方括号指定有效的索引值来访问数组的元素: someArray[0] 指的是索引为 0 的元素 "Alex"。

You can create multidimensional arrays by nesting pairs of square brackets, where the name of the base type of the elements is contained in the innermost pair of square brackets. For example, you can create a three-dimensional array of integers using three sets of square brackets:

你可以通过嵌套方括号对来创建多维数组,其中基本元素类型的名称包含在最内层的方括号对中。 例如,你可以使用三组方括号创建一个三维整数数组:

var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

When accessing the elements in a multidimensional array, the left-most subscript index refers to the element at that index in the outermost array. The next subscript index to the right refers to the element at that index in the array that's nested one level in. And so on. This means that in the example above, array3D[0] refers to [[1, 2], [3, 4]], array3D[0][1] refers to [3, 4], and array3D[0][1][1] refers to the value 4.

当访问多维数组的元素时,最左边的下标索引指的是最外层数组中该索引处的元素。下一个向右的下标索引指的是嵌套一层的数组中该索引处的元素。以此类推。这意味着在上面的示例中,array3D[0] 指的是 [[1, 2], [3, 4]]、array3D[0][1] 指的是 [3, 4]、array3D[0][1][1] 指的是值 4。

For a detailed discussion of the Swift standard library Array type, see Arrays.

有关 Swift 标准库 Array 类型的详细讨论,请参阅 数组。

Grammar of an array type

  • array-type → [ type ]

Dictionary Type 字典类型

The Swift language provides the following syntactic sugar for the Swift standard library Dictionary<Key, Value> type:

Swift 语言为 Swift 标准库 Dictionary<Key, Value> 类型提供了以下语法糖:

[<#key type#>: <#value type#>]

In other words, the following two declarations are equivalent:

换句话说,以下两个声明是等价的:

let someDictionary: [String: Int] = ["Alex": 31, "Paul": 39]
let someDictionary: Dictionary<String, Int> = ["Alex": 31, "Paul": 39]

In both cases, the constant someDictionary is declared as a dictionary with strings as keys and integers as values.

在这两种情况下,常量 someDictionary 都被声明为一个以字符串作为键、整数作为值的字典。

The values of a dictionary can be accessed through subscripting by specifying the corresponding key in square brackets: someDictionary["Alex"] refers to the value associated with the key "Alex". The subscript returns an optional value of the dictionary's value type. If the specified key isn't contained in the dictionary, the subscript returns nil.

可以通过在方括号中指定相应的键来访问字典的值:someDictionary["Alex"] 指的是与键 "Alex" 关联的值。 下标返回字典值类型的可选值。 如果指定的键不在字典中,下标将返回 nil。

The key type of a dictionary must conform to the Swift standard library Hashable protocol.

字典的键类型必须符合 Swift 标准库 Hashable 协议。

For a detailed discussion of the Swift standard library Dictionary type, see Dictionaries.

有关 Swift 标准库 Dictionary 类型的详细讨论,请参阅 字典。

Grammar of a dictionary type

  • dictionary-type → [ type : type ]

Optional Type 可选类型

The Swift language defines the postfix ? as syntactic sugar for the named type Optional<Wrapped>, which is defined in the Swift standard library. In other words, the following two declarations are equivalent:

Swift 语言将后缀 ? 定义为命名类型 Optional<Wrapped> 的语法糖,该类型定义在 Swift 标准库中。换句话说,以下两个声明是等价的:

var optionalInteger: Int?
var optionalInteger: Optional<Int>

In both cases, the variable optionalInteger is declared to have the type of an optional integer. Note that no whitespace may appear between the type and the ?.

在这两种情况下,变量 optionalInteger 都被声明为可选整数类型。注意,类型和 ? 之间不能有空格。

The type Optional<Wrapped> is an enumeration with two cases, none and some(Wrapped), which are used to represent values that may or may not be present. Any type can be explicitly declared to be (or implicitly converted to) an optional type. If you don't provide an initial value when you declare an optional variable or property, its value automatically defaults to nil.

Optional<Wrapped> 类型是一个枚举,有两个成员 none 和 some(Wrapped),用于表示可能存在也可能不存在的值。任何类型都可以被显式声明为(或隐式转换为)可选类型。如果在声明可选变量或属性时没有提供初始值,它的值会自动默认为 nil。

If an instance of an optional type contains a value, you can access that value using the postfix operator !, as shown below:

如果一个可选类型的实例包含值,你可以使用后缀运算符 ! 访问该值,如下所示:

optionalInteger = 42
optionalInteger! // 42

Using the ! operator to unwrap an optional that has a value of nil results in a runtime error.

使用 ! 运算符解包值为 nil 的可选值会导致运行时错误。

You can also use optional chaining and optional binding to conditionally perform an operation on an optional expression. If the value is nil, no operation is performed and therefore no runtime error is produced.

你也可以使用可选链和可选绑定来有条件地对可选表达式执行操作。如果值为 nil,则不执行任何操作,因此也不会产生运行时错误。

For more information and to see examples that show how to use optional types, see Optionals.

有关可选类型的更多信息以及演示如何使用可选类型的示例,请参阅 可选。

Grammar of an optional type

  • optional-type → type ?

Implicitly Unwrapped Optional Type 隐式解包可选类型

The Swift language defines the postfix ! as syntactic sugar for the named type Optional<Wrapped>, which is defined in the Swift standard library, with the additional behavior that it's automatically unwrapped when it's accessed. If you try to use an implicitly unwrapped optional that has a value of nil, you'll get a runtime error. With the exception of the implicit unwrapping behavior, the following two declarations are equivalent:

Swift 语言将后缀 ! 定义为命名类型 Optional<Wrapped> 的语法糖,该类型定义在 Swift 标准库中,附加行为是在访问时会自动解包。如果尝试使用值为 nil 的隐式解包可选值,你会得到一个运行时错误。除了隐式解包这一行为之外,以下两个声明是等价的:

var implicitlyUnwrappedString: String!
var explicitlyUnwrappedString: Optional<String>

Note that no whitespace may appear between the type and the !.

注意,类型和 ! 之间不能有空格。

Because implicit unwrapping changes the meaning of the declaration that contains that type, optional types that are nested inside a tuple type or a generic type --- such as the element types of a dictionary or array --- can't be marked as implicitly unwrapped. For example:

由于隐式解包会改变包含该类型的声明的含义,嵌套在元组类型或泛型类型(例如字典或数组的元素类型)中的可选类型不能被标记为隐式解包。例如:

let tupleOfImplicitlyUnwrappedElements: (Int!, Int!)  // Error
let implicitlyUnwrappedTuple: (Int, Int)!             // OK

let arrayOfImplicitlyUnwrappedElements: [Int!]        // Error
let implicitlyUnwrappedArray: [Int]!                  // OK

Because implicitly unwrapped optionals have the same Optional<Wrapped> type as optional values, you can use implicitly unwrapped optionals in all the same places in your code that you can use optionals. For example, you can assign values of implicitly unwrapped optionals to variables, constants, and properties of optionals, and vice versa.

由于隐式解包可选值与可选值具有相同的 Optional<Wrapped> 类型,因此在任何可以使用可选值的地方,也可以使用隐式解包可选值。例如,你可以将隐式解包可选值赋值给可选变量、常量和属性,反之亦然。

As with optionals, if you don't provide an initial value when you declare an implicitly unwrapped optional variable or property, its value automatically defaults to nil.

与可选值一样,如果在声明隐式解包可选变量或属性时没有提供初始值,它的值会自动默认为 nil。

Use optional chaining to conditionally perform an operation on an implicitly unwrapped optional expression. If the value is nil, no operation is performed and therefore no runtime error is produced.

使用可选链来有条件地对隐式解包可选表达式执行操作。如果值为 nil,则不执行任何操作,因此也不会产生运行时错误。

For more information about implicitly unwrapped optional types, see Implicitly Unwrapped Optionals.

有关隐式解包可选类型的更多信息,请参阅 隐式解包可选。

Grammar of an implicitly unwrapped optional type

  • implicitly-unwrapped-optional-type → type !

Protocol Composition Type 协议组合类型

A protocol composition type defines a type that conforms to each protocol in a list of specified protocols, or a type that's a subclass of a given class and conforms to each protocol in a list of specified protocols. Protocol composition types may be used only when specifying a type in type annotations, in generic parameter clauses, and in generic where clauses.

协议组合类型定义了一种遵循指定协议列表中每个协议的类型,或者一种是给定类的子类并遵循指定协议列表中每个协议的类型。协议组合类型只能在类型注解、泛型形参子句和泛型 where 子句中指定类型时使用。

Protocol composition types have the following form:

协议组合类型具有以下形式:

<#Protocol 1#> & <#Protocol 2#>

A protocol composition type allows you to specify a value whose type conforms to the requirements of multiple protocols without explicitly defining a new, named protocol that inherits from each protocol you want the type to conform to. For example, you can use the protocol composition type ProtocolA & ProtocolB & ProtocolC instead of declaring a new protocol that inherits from ProtocolA, ProtocolB, and ProtocolC. Likewise, you can use SuperClass & ProtocolA instead of declaring a new protocol that's a subclass of SuperClass and conforms to ProtocolA.

协议组合类型允许你指定一个值的类型符合多个协议的要求,而无需显式定义一个新的命名协议来继承你希望该类型符合的每个协议。你可以使用协议组合类型ProtocolA & ProtocolB & ProtocolC而不是声明一个新的协议继承自ProtocolA、ProtocolB和ProtocolC。同样,你可以使用SuperClass & ProtocolA而不是声明一个新的协议,该协议是SuperClass的子类并符合ProtocolA。

Each item in a protocol composition list is one of the following; the list can contain at most one class:

协议组合列表中的每一项都是以下之一,列表最多可以包含一个类:

  • The name of a class
  • The name of a protocol
  • A type alias whose underlying type is a protocol composition type, a protocol, or a class.
  • 类的名称
  • 协议的名称
  • 底层类型是协议组合类型、协议或类的类型别名

When a protocol composition type contains type aliases, it's possible for the same protocol to appear more than once in the definitions --- duplicates are ignored. For example, the definition of PQR in the code below is equivalent to P & Q & R.

当协议组合类型包含类型别名时,同一协议可能会在定义中出现多次,重复项会被忽略。例如,下面代码中PQR的定义等同于P & Q & R。

typealias PQ = P & Q
typealias PQR = PQ & Q & R

Grammar of a protocol composition type

  • protocol-composition-type → type-identifier & protocol-composition-continuation
  • protocol-composition-continuation → type-identifier | protocol-composition-type

Opaque Type 不透明类型

An opaque type defines a type that conforms to a protocol or protocol composition, without specifying the underlying concrete type.

不透明类型定义了一种遵循某个协议或协议组合的类型,而不指定底层的具体类型。

Opaque types appear as the return type of a function or subscript, as the type of a parameter to a function, subscript, or initializer, or as the type of a property. Opaque types can't appear as part of a tuple type or a generic type, such as the element type of an array or the wrapped type of an optional.

不透明类型可以作为函数或下标的返回类型、函数、下标或构造器的形参类型,或者属性的类型出现。不透明类型不能作为元组类型或泛型类型的一部分出现,例如数组的元素类型或可选类型的被包装类型。

Opaque types have the following form:

不透明类型具有以下形式:

some <#constraint#>

The constraint is a class type, protocol type, protocol composition type, or Any. A value can be used as an instance of the opaque type only if it's an instance of a type that conforms to the listed protocol or protocol composition, or inherits from the listed class. Code that interacts with an opaque value can use the value only in ways that are part of the interface defined by the constraint.

约束是类类型、协议类型、协议组合类型或 Any。只有当一个值是遵循所列协议或协议组合的类型的实例,或者继承自所列的类时,才能将该值用作不透明类型的实例。与不透明值交互的代码只能以约束所定义接口中的方式使用该值。

At compile time, a value whose type is opaque has a specific concrete type, and Swift can use that underlying type for optimizations. However, the opaque type forms a boundary that information about that underlying type can't cross.

约束是类类型、协议类型、协议组合类型或Any。只有当值是符合列出的协议或协议组合的类型实例,或者从列出的类继承时,才能将该值用作不透明类型的实例。与不透明值交互的代码只能以约束定义的接口中的方式使用该值。

Protocol declarations can't include opaque types. Classes can't use an opaque type as the return type of a nonfinal method.

协议声明不能包含不透明类型。类不能将不透明类型用作非 final 方法的返回类型。

A function that uses an opaque type as its return type must return values that share a single underlying type. The return type can include types that are part of the function's generic type parameters. For example, a function someFunction<T>() could return a value of type T or Dictionary<String, T>.

使用不透明类型作为返回类型的函数,必须返回共享同一个底层类型的值。返回类型可以包含作为函数泛型类型形参一部分的类型。例如,函数 someFunction<T>() 可以返回类型为 T 或 Dictionary<String, T> 的值。

Writing an opaque type for a parameter is syntactic sugar for using a generic type, without specifying a name for the generic type parameter. The implicit generic type parameter has a constraint that requires it to conform to the protocol named in the opaque type. If you write multiple opaque types, each one makes its own generic type parameter. For example, the following declarations are equivalent:

为形参编写不透明类型,是使用泛型类型而不为泛型类型形参指定名称的语法糖。这个隐式的泛型类型形参带有一个约束,要求它遵循不透明类型中指定的协议。如果你编写了多个不透明类型,每一个都会生成各自的泛型类型形参。例如,以下声明是等价的:

func someFunction(x: some MyProtocol, y: some MyProtocol) { }
func someFunction<T1: MyProtocol, T2: MyProtocol>(x: T1, y: T2) { }

In the second declaration, because the generic type parameters T1 and T2 have names, you can refer use these types elsewhere in the code. In contrast, the generic type parameters in the first declaration don't have names and can't be referenced in other code.

在第二个声明中,由于泛型类型形参 T1 和 T2 有名称,你可以在代码的其他地方使用这些类型。相比之下,第一个声明中的泛型类型形参没有名称,无法在其他代码中引用。

You can't use an opaque type in the type of a variadic parameter.

不能在可变参数的类型中使用不透明类型。

You can't use an opaque type as a parameter to a function type being returned, or as a parameter in a parameter type that's a function type. In these positions, the function's caller would have to construct a value of that unknown type.

不能将不透明类型用作被返回的函数类型的形参,也不能用作函数类型形参中的形参。在这些位置上,函数的调用者将不得不构造一个未知类型的值。

protocol MyProtocol { }
func badFunction() -> (some MyProtocol) -> Void { }  // Error
func anotherBadFunction(callback: (some MyProtocol) -> Void) { }  // Error

Grammar of an opaque type

  • opaque-type → some type

Boxed Protocol Type 封装协议类型

A boxed protocol type defines a type that conforms to a protocol or protocol composition, with the ability for that conforming type to vary while the program is running.

封装协议类型定义了一种遵循某个协议或协议组合的类型,并且这个遵循类型可以在程序运行时变化。

Boxed protocol types have the following form:

封装协议类型具有以下形式:

any <#constraint#>

The constraint is a protocol type, protocol composition type, a metatype of a protocol type, or a metatype of a protocol composition type.

约束是协议类型、协议组合类型、协议类型的元类型或协议组合类型的元类型。

At runtime, an instance of a boxed protocol type can contain a value of any type that satisfies the constraint. This behavior contrasts with how an opaque types work, where there is some specific conforming type known at compile time. The additional level of indirection that's used when working with a boxed protocol type is called boxing. Boxing typically requires a separate memory allocation for storage and an additional level of indirection for access, which incurs a performance cost at runtime.

在运行时,封装协议类型的实例可以包含满足约束的任意类型的值。这与不透明类型的工作方式形成对比,不透明类型在编译时就知道某个具体的遵循类型。使用封装协议类型时所用的额外间接层称为装箱(boxing)。装箱通常需要单独分配内存用于存储,并且访问时需要额外的间接层,这会在运行时产生性能开销。

Applying any to the Any or AnyObject types has no effect, because those types are already boxed protocol types.

对 Any 或 AnyObject 类型应用 any 没有任何效果,因为这些类型已经是封装协议类型。

Grammar of a boxed protocol type

  • boxed-protocol-type → any type

Metatype Type 元类型

A metatype type refers to the type of any type, including class types, structure types, enumeration types, and protocol types.

元类型指的是描述一个类型本身的类型,包括类类型、结构体类型、枚举类型和协议类型。

The metatype of a class, structure, or enumeration type is the name of that type followed by .Type. The metatype of a protocol type --- not the concrete type that conforms to the protocol at runtime --- is the name of that protocol followed by .Protocol. For example, the metatype of the class type SomeClass is SomeClass.Type and the metatype of the protocol SomeProtocol is SomeProtocol.Protocol.

类、结构体或枚举类型的元类型是该类型的名称后跟 .Type。协议类型的元类型(而不是运行时遵循该协议的具体类型)是该协议的名称后跟 .Protocol。例如,类类型 SomeClass 的元类型是 SomeClass.Type,协议 SomeProtocol 的元类型是 SomeProtocol.Protocol。

You can use the postfix self expression to access a type as a value. For example, SomeClass.self returns SomeClass itself, not an instance of SomeClass. And SomeProtocol.self returns SomeProtocol itself, not an instance of a type that conforms to SomeProtocol at runtime. You can call the type(of:) function with an instance of a type to access that instance's dynamic, runtime type as a value, as the following example shows:

你可以使用后缀 self 表达式以值的形式访问一个类型。例如,SomeClass.self 返回 SomeClass 本身,而不是 SomeClass 的实例。SomeProtocol.self 返回 SomeProtocol 本身,而不是运行时遵循 SomeProtocol 的某个类型的实例。你可以将一个类型的实例传给 type(of:) 函数,以值的形式访问该实例的动态运行时类型,如下例所示:

class SomeBaseClass {
    class func printClassName() {
        print("SomeBaseClass")
    }
}
class SomeSubClass: SomeBaseClass {
    override class func printClassName() {
        print("SomeSubClass")
    }
}
let someInstance: SomeBaseClass = SomeSubClass()
// The compile-time type of someInstance is SomeBaseClass,
// and the runtime type of someInstance is SomeSubClass
type(of: someInstance).printClassName()
// Prints "SomeSubClass".

For more information, see type(of:) in the Swift standard library.

更多信息,请参阅 Swift 标准库中的 type(of:)。

Use an initializer expression to construct an instance of a type from that type's metatype value. For class instances, the initializer that's called must be marked with the required keyword or the entire class marked with the final keyword.

使用构造器表达式可以通过类型的元类型值构造该类型的实例。对于类实例,被调用的构造器必须用 required 关键字标记,或者整个类用 final 关键字标记。

class AnotherSubClass: SomeBaseClass {
    let string: String
    required init(string: String) {
        self.string = string
    }
    override class func printClassName() {
        print("AnotherSubClass")
    }
}
let metatype: AnotherSubClass.Type = AnotherSubClass.self
let anotherInstance = metatype.init(string: "some string")

Grammar of a metatype type

  • metatype-type → type . Type | type . Protocol

Any Type Any 类型

The Any type can contain values from all other types. Any can be used as the concrete type for an instance of any of the following types:

Any 类型可以包含来自所有其他类型的值。 Any 可以用作以下任何类型实例的具体类型:

  • A class, structure, or enumeration
  • A metatype, such as Int.self
  • A tuple with any types of components
  • A closure or function type
  • 类、结构或枚举
  • 元类型,如 Int.self
  • 具有任何类型组件的元组
  • 闭包或函数类型
let mixed: [Any] = ["one", 2, true, (4, 5.3), { () -> Int in return 6 }]

When you use Any as a concrete type for an instance, you need to cast the instance to a known type before you can access its properties or methods. Instances with a concrete type of Any maintain their original dynamic type and can be cast to that type using one of the type-cast operators --- as, as?, or as!. For example, use as? to conditionally downcast the first object in a heterogeneous array to a String as follows:

当你使用 Any 作为实例的具体类型时,你需要在访问其属性或方法之前将实例转换为已知类型。 具有 Any 具体类型的实例保持其原始动态类型,并且可以使用类型转换运算符 --- as、as? 或 as! 转换为该类型。 例如,使用 as? 有条件地将异构数组中的第一个对象向下转换为 String,如下所示:

if let first = mixed.first as? String {
    print("The first item, '\(first)', is a string.")
}
// Prints "The first item, 'one', is a string."

For more information about casting, see Type Casting.

有关转换的更多信息,请参阅 类型转换。

The AnyObject protocol is similar to the Any type. All classes implicitly conform to AnyObject. Unlike Any, which is defined by the language, AnyObject is defined by the Swift standard library. For more information, see Class-Only Protocols and AnyObject.

AnyObject 协议类似于 Any 类型。 所有类型都隐式符合 AnyObject。 与由语言定义的 Any 不同, AnyObject 由 Swift 标准库定义。 有关更多信息,请参阅 类专属的协议 和 AnyObject。

Grammar of an Any type

  • any-type → Any

Self Type Self 类型

The Self type isn't a specific type, but rather lets you conveniently refer to the current type without repeating or knowing that type's name.

Self 类型不是特定类型,而是让你方便地引用当前类型而无需重复或知道该类型的名称。

In a protocol declaration or a protocol member declaration, the Self type refers to the eventual type that conforms to the protocol.

在协议声明或协议成员声明中, Self 类型指的是最终符合该协议的类型。

In a structure, class, or enumeration declaration, the Self type refers to the type introduced by the declaration. Inside the declaration for a member of a type, the Self type refers to that type. In the members of a class declaration, Self can appear only as follows:

在结构、类或枚举声明中, Self 类型指的是由声明引入的类型。 在类型成员的声明中, Self 类型指的是该类型。 在类声明的成员中, Self 只能出现在以下位置:

  • As the return type of a method
  • As the return type of a read-only subscript
  • As the type of a read-only computed property
  • In the body of a method
  • 作为方法的返回类型
  • 作为只读下标的返回类型
  • 作为只读计算属性的类型
  • 在方法体内

For example, the code below shows an instance method f whose return type is Self.

例如,下面的代码显示了一个实例方法 f,其返回类型是 Self。

class Superclass {
    func f() -> Self { return self }
}
let x = Superclass()
print(type(of: x.f()))
// Prints "Superclass".

class Subclass: Superclass { }
let y = Subclass()
print(type(of: y.f()))
// Prints "Subclass".

let z: Superclass = Subclass()
print(type(of: z.f()))
// Prints "Subclass".

The last part of the example above shows that Self refers to the runtime type Subclass of the value of z, not the compile-time type Superclass of the variable itself.

上面例子的最后一部分表明,Self 指的是 z 的值的运行时类型 Subclass,而不是变量本身的编译时类型 Superclass。

Inside a nested type declaration, the Self type refers to the type introduced by the innermost type declaration.

在嵌套类型声明中,Self 类型指的是最内层类型声明所引入的类型。

The Self type refers to the same type as the type(of:) function in the Swift standard library. Writing Self.someStaticMember to access a member of the current type is the same as writing type(of: self).someStaticMember.

Self 类型与 Swift 标准库中 type(of:) 函数所指的类型相同。编写 Self.someStaticMember 来访问当前类型的成员,与编写 type(of: self).someStaticMember 是一样的。

Grammar of a Self type

  • self-type → Self

Type Inheritance Clause 类型继承子句

A type inheritance clause is used to specify which class a named type inherits from and which protocols a named type conforms to. A type inheritance clause begins with a colon (:), followed by a list of type identifiers.

类型继承子句 用于指定命名类型继承自哪个类以及符合哪些协议。类型继承子句以冒号 (:) 开头,后跟一系列类型标识符。

Class types can inherit from a single superclass and conform to any number of protocols. When defining a class, the name of the superclass must appear first in the list of type identifiers, followed by any number of protocols the class must conform to. If the class doesn't inherit from another class, the list can begin with a protocol instead. For an extended discussion and several examples of class inheritance, see Inheritance.

类可以继承自单个超类并符合任意数量的协议。在定义类时,超类的名称必须出现在类型标识符列表的首位,后跟该类必须符合的任意数量的协议。如果该类不继承自其他类,则列表可以从协议开始。有关类继承的扩展讨论和几个示例,请参阅 继承。

Other named types can only inherit from or conform to a list of protocols. Protocol types can inherit from any number of other protocols. When a protocol type inherits from other protocols, the set of requirements from those other protocols are aggregated together, and any type that inherits from the current protocol must conform to all of those requirements. Writing a tilde (~) in front of a protocol name in this list suppresses an implicit conformance to that protocol, as described in Implicit Conformance to a Protocol.

其他命名类型只能继承自或遵循一系列协议。协议类型可以继承自任意数量的其他协议。当一个协议类型继承自其他协议时,来自那些协议的要求会被聚合在一起,任何继承自当前协议的类型都必须满足所有这些要求。在此列表中的协议名称前面写波浪号(~)会抑制对该协议的隐式遵循,如 对协议的隐式遵循 中所述。

A type inheritance clause in an enumeration definition can be either a list of protocols, or in the case of an enumeration that assigns raw values to its cases, a single, named type that specifies the type of those raw values. For an example of an enumeration definition that uses a type inheritance clause to specify the type of its raw values, see Raw Values.

对于为枚举案例分配原始值的枚举定义,类型继承子句可以是指定这些原始值类型的单个命名类型。有关使用类型继承子句指定其原始值类型的枚举定义示例,请参阅 原始值。

Grammar of a type inheritance clause

  • type-inheritance-clause → : type-inheritance-list
  • type-inheritance-list → attributes? ~? type-identifier | attributes? ~? type-identifier , type-inheritance-list

Type Inference 类型推断

Swift uses type inference extensively, allowing you to omit the type or part of the type of many variables and expressions in your code. For example, instead of writing var x: Int = 0, you can write var x = 0, omitting the type completely --- the compiler correctly infers that x names a value of type Int. Similarly, you can omit part of a type when the full type can be inferred from context. For example, if you write let dict: Dictionary = ["A": 1], the compiler infers that dict has the type Dictionary<String, Int>.

Swift 广泛使用类型推断,允许你在代码中省略许多变量和表达式的类型或部分类型。例如,你可以写 var x = 0 来代替 var x: Int = 0,完全省略类型——编译器会正确推断出 x 是 Int 类型的值。同样,当完整类型可以从上下文推断出来时,你可以省略部分类型。例如,如果你写 let dict: Dictionary = ["A": 1],编译器会推断出 dict 的类型是 Dictionary<String, Int>。

In both of the examples above, the type information is passed up from the leaves of the expression tree to its root. That is, the type of x in var x: Int = 0 is inferred by first checking the type of 0 and then passing this type information up to the root (the variable x).

在上面的两个示例中,类型信息从表达式树的叶子传递到根部。也就是说,var x: Int = 0 中 x 的类型是通过首先检查 0 的类型,然后将此类型信息传递至根 (变量 x) 来推断的。

In Swift, type information can also flow in the opposite direction --- from the root down to the leaves. In the following example, for instance, the explicit type annotation (: Float) on the constant eFloat causes the numeric literal 2.71828 to have an inferred type of Float instead of Double.

在 Swift 中,类型信息也可以从根向下流向叶子节点。例如,在下面的例子中,常量 eFloat 使得数字字面量 (: Float) 导致数字字面量 2.71828 被推断为 Float 类型,而不是 Double 类型。

let e = 2.71828 // The type of e is inferred to be Double.
let eFloat: Float = 2.71828 // The type of eFloat is Float.

Type inference in Swift operates at the level of a single expression or statement. This means that all of the information needed to infer an omitted type or part of a type in an expression must be accessible from type-checking the expression or one of its subexpressions.

Swift 的类型推断是在单个表达式或语句层级进行的。这意味着推断一个省略的类型或表达式中部分类型所需的所有信息,必须可从类型检查该表达式或其子表达式中获得。

On this page