Initialization构造过程
Set the initial values for a type's stored properties and perform one-time setup.
为类型的存储属性设置初始值,并执行一次性的设置工作。
Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that's required before the new instance is ready for use.
构造过程是使用类、结构体或枚举等实例之前的准备过程。这个过程包括为该实例的每个存储属性设置初始值,并执行任何其他必要的设置或构造过程,以确保新实例在使用前已经完成正确的构造。
You implement this initialization process by defining initializers, which are like special methods that can be called to create a new instance of a particular type. Unlike Objective-C initializers, Swift initializers don't return a value. Their primary role is to ensure that new instances of a type are correctly initialized before they're used for the first time.
你可以通过定义构造器来实现这个构造过程,它就像是用来创建特定类型新实例的特殊方法。与Objective-C构造器不同,Swift构造器没有返回值,它们的主要作用是确保类型的新实例在首次使用前被正确构造。
Instances of class types can also implement a deinitializer, which performs any custom cleanup just before an instance of that class is deallocated. For more information about deinitializers, see Deinitialization.
类的实例可以通过实现析构器来执行它释放之前自定义的清理工作。想了解析构器的更多内容,请参见 析构过程。
Setting Initial Values for Stored Properties 存储属性的初始赋值
Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties can't be left in an indeterminate state.
创建类和结构体的实例时,必须为它们所有的存储属性设置一个适当的初始值。存储属性不能处于不确定的状态。
You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property's definition. These actions are described in the following sections.
你可以在构造器中为存储属性设置初始值,或者在定义属性时赋予默认值。以下部分将会详细介绍这两种方法。
Note · 注意
When you assign a default value to a stored property, or set its value within an initializer, the value of that property is set directly, without calling any property observers.
当你为存储属性赋予默认值,或者在构造器中设置其值时,该属性的值会被直接设置,而不会触发任何属性观察器。
Initializers 构造器
Initializers are called to create a new instance of a particular type.
In its simplest form, an initializer is like an instance method with no parameters,
written using the init keyword:
构造器 被调用来创建某个特定类型的新实例。构造器在最简单的形式中就像一个没有参数的实例方法,以关键字init 来命名:
init() {
// perform some initialization here
}The example below defines a new structure called Fahrenheit
to store temperatures expressed in the Fahrenheit scale.
The Fahrenheit structure has one stored property,
temperature, which is of type Double:
下面例子中定义了一个用来保存华氏温度的结构体 Fahrenheit,它拥有一个 Double 类型的存储型属性 temperature:
struct Fahrenheit {
var temperature: Double
init() {
temperature = 32.0
}
}
var f = Fahrenheit()
print("The default temperature is \(f.temperature)° Fahrenheit")
// Prints "The default temperature is 32.0° Fahrenheit".The structure defines a single initializer, init, with no parameters,
which initializes the stored temperature with a value of 32.0
(the freezing point of water in degrees Fahrenheit).
这个结构体只定义了一个不带形参的构造器 init,并在里面将存储型属性 temperature 的值初始化为 32.0(华氏温度下水的冰点)。
Default Property Values 默认属性值
You can set the initial value of a stored property from within an initializer, as shown above. Alternatively, specify a default property value as part of the property's declaration. You specify a default property value by assigning an initial value to the property when it's defined.
如上所示,你可以在构造器中设置存储属性的初始值。同样,你也可以在属性声明时为其设置默认值。
Note · 注意
If a property always takes the same initial value, provide a default value rather than setting a value within an initializer. The end result is the same, but the default value ties the property's initialization more closely to its declaration. It makes for shorter, clearer initializers and enables you to infer the type of the property from its default value. The default value also makes it easier for you to take advantage of default initializers and initializer inheritance, as described later in this chapter.
如果一个属性总是使用相同的初始值,建议直接提供一个默认值,而不是每次都在构造器中设置值。两种方法的最终结果是一样的,但默认值使属性的初始化与其声明结合的更加紧密。它能让你的构造器更简洁、更清晰,且能够通过默认值推断属性的类型。默认值还能使你更容易利用默认构造器和构造器继承等特性,如本章后面所述。
You can write the Fahrenheit structure from above in a simpler form
by providing a default value for its temperature property
at the point that the property is declared:
你可以通过在声明 temperature 属性时提供一个默认值,将上面的 Fahrenheit 结构体写成如下更简单的形式:
struct Fahrenheit {
var temperature = 32.0
}Customizing Initialization 自定义构造过程
You can customize the initialization process with input parameters and optional property types, or by assigning constant properties during initialization, as described in the following sections.
你可以自定义构造过程,比如提供输入的形参、可选属性类型或者给常量属性赋值,这些都将在后面章节中提到。
Initialization Parameters 形参的构造过程
You can provide initialization parameters as part of an initializer's definition, to define the types and names of values that customize the initialization process. Initialization parameters have the same capabilities and syntax as function and method parameters.
你可以在自定义构造过程的定义中提供构造形参,指定其值的类型和名字。构造形参的功能和语法与函数和方法的形参相同。
The following example defines a structure called Celsius,
which stores temperatures expressed in degrees Celsius.
The Celsius structure implements two custom initializers called
init(fromFahrenheit:) and init(fromKelvin:),
which initialize a new instance of the structure
with a value from a different temperature scale:
下面例子中定义了一个用来保存摄氏温度的结构体 Celsius。它定义了两个不同的构造器:init(fromFahrenheit:) 和 init(fromKelvin:),二者分别通过接受不同温标下的温度值来创建新的实例:
struct Celsius {
var temperatureInCelsius: Double
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
}
}
let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
// boilingPointOfWater.temperatureInCelsius is 100.0
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
// freezingPointOfWater.temperatureInCelsius is 0.0The first initializer has a single initialization parameter
with an argument label of fromFahrenheit and a parameter name of fahrenheit.
The second initializer has a single initialization parameter
with an argument label of fromKelvin and a parameter name of kelvin.
Both initializers convert their single argument into
the corresponding Celsius value
and store this value in a property called temperatureInCelsius.
第一个构造器只拥有一个构造形参,其实参标签为 fromFahrenheit,形参命名为 fahrenheit;第二个构造器也拥有一个构造形参,其实参标签为 fromKelvin,形参命名为 kelvin。这两个构造器都将单一的实参转换成摄氏温度值,并保存在属性 temperatureInCelsius 中。
Parameter Names and Argument Labels 形参命名和实参标签
As with function and method parameters, initialization parameters can have both a parameter name for use within the initializer's body and an argument label for use when calling the initializer.
与函数和方法形参相同,构造形参可以同时具有在构造器内部使用的形参名称和在调用构造器时使用的实参标签。
However, initializers don't have an identifying function name before their parentheses in the way that functions and methods do. Therefore, the names and types of an initializer's parameters play a particularly important role in identifying which initializer should be called. Because of this, Swift provides an automatic argument label for every parameter in an initializer if you don't provide one.
然而,构造器在括号前没有像函数和方法那样的可辨别的方法名。因此,构造器的形参名称和类型在确定应调用哪个构造器时起着至关重要的作用。正因为如此,如果你没有提供实参标签,Swift会为构造器的每个形参自动提供一个实参标签。
The following example defines a structure called Color,
with three constant properties called red, green, and blue.
These properties store a value between 0.0 and 1.0
to indicate the amount of red, green, and blue in the color.
下面例子中的 Color 结构体包含了三个 Double 类型的常量( red 、 green、 blue ),表明颜色中红、绿、蓝成分的含量。
Color 提供了一个构造器,为红蓝绿提供三个合适 Double 类型的形参命名。Color 也提供了第二个构造器,它只包含名为 white 的 Double 类型的形参,它为三个颜色的属性提供相同的值。
Color provides an initializer with
three appropriately named parameters of type Double
for its red, green, and blue components.
Color also provides a second initializer with a single white parameter,
which is used to provide the same value for all three color components.
Color 提供了一个构造器,它有三个类型为 Double、名称恰当的形参,分别对应红、绿、蓝三个分量。Color 还提供了第二个构造器,它只有一个 white 形参,用于为三个颜色分量提供相同的值。
struct Color {
let red, green, blue: Double
init(red: Double, green: Double, blue: Double) {
self.red = red
self.green = green
self.blue = blue
}
init(white: Double) {
red = white
green = white
blue = white
}
}Both initializers can be used to create a new Color instance,
by providing named values for each initializer parameter:
两种构造器都能通过为每一个构造器形参提供具名的值来创建一个新的 Color 实例:
let magenta = Color(red: 1.0, green: 0.0, blue: 1.0)
let halfGray = Color(white: 0.5)Note that it isn't possible to call these initializers without using argument labels. Argument labels must always be used in an initializer if they're defined, and omitting them is a compile-time error:
注意,调用这些构造器时不能省略实参标签。如果构造器中定义了实参标签,就必须始终使用它们,省略它们会导致编译时错误:
let veryGreen = Color(0.0, 1.0, 0.0)
// this reports a compile-time error - argument labels are requiredInitializer Parameters Without Argument Labels 不带实参标签的构造器形参
If you don't want to use an argument label for an initializer parameter,
write an underscore (_) instead of an explicit argument label for that parameter
to override the default behavior.
如果你不希望构造器的某个形参使用实参标签,可以使用下划线(_)来代替该形参的显式实参标签,以覆盖默认行为。
Here's an expanded version of the Celsius example
from Initialization Parameters above,
with an additional initializer to create a new Celsius instance
from a Double value that's already in the Celsius scale:
接下来是 形参的构造过程 带来的扩展版本的 Celsius, 增加了一个构造器用于从已经是摄氏温标的 Double 值创建一个新的 Celsius 实例:
struct Celsius {
var temperatureInCelsius: Double
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
}
init(_ celsius: Double) {
temperatureInCelsius = celsius
}
}
let bodyTemperature = Celsius(37.0)
// bodyTemperature.temperatureInCelsius is 37.0The initializer call Celsius(37.0) is clear in its intent
without the need for an argument label.
It's therefore appropriate to write this initializer as init(_ celsius: Double)
so that it can be called by providing an unnamed Double value.
构造器调用 Celsius(37.0) 的意图非常明确,不需要实参标签。因此,适合使用构造器 init(_ celsius: Double)来通过未命名的 Double 值来构造 Celsius 。
Optional Property Types 可选属性类型
If your custom type has a stored property that's logically allowed to have “no value” ---
perhaps because its value can't be set during initialization,
or because it's allowed to have “no value” at some later point ---
declare the property with an optional type.
Properties of optional type are automatically initialized with a value of nil,
indicating that the property is deliberately intended to have “no value yet”
during initialization.
如果你自定义的类型有一个逻辑上允许值为空的存储型属性——无论是因为它无法在初始化时赋值,还是因为它在之后某个时机可以赋值为空——都需要将它声明为可选类型。可选类型的属性将自动初始化为 nil,表示这个属性是特意在构造过程设置为空。
The following example defines a class called SurveyQuestion,
with an optional String property called response:
下面例子中定义了类 SurveyQuestion,它包含一个可选 String 属性 response:
class SurveyQuestion {
var text: String
var response: String?
init(text: String) {
self.text = text
}
func ask() {
print(text)
}
}
let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
cheeseQuestion.ask()
// Prints "Do you like cheese?"
cheeseQuestion.response = "Yes, I do like cheese."The response to a survey question can't be known until it's asked,
and so the response property is declared with a type of String?,
or “optional String”.
It's automatically assigned a default value of nil, meaning “no string yet”,
when a new instance of SurveyQuestion is initialized.
对调查问卷问题的答案,唯有提问后方能揭晓,因此 response 属性被声明为 String? 类型,即“可选的 String ”。当一个新的 SurveyQuestion 实例被初始化时,它会自动被赋予默认值 nil,表示“尚无字符串”。
Assigning Constant Properties During Initialization 构造过程中常量属性的赋值
You can assign a value to a constant property at any point during initialization, as long as it's set to a definite value by the time initialization finishes. Once a constant property is assigned a value, it can't be further modified.
你可以在构造过程中的任意时间点给常量属性赋值,只要在构造过程结束时将它设置成确定的值。一旦常量属性被赋值,它将永远不可更改。
Note · 注意
For class instances, a constant property can be modified during initialization only by the class that introduces it. It can't be modified by a subclass.
对于类的实例来说,它的常量属性只能在类的构造过程中修改,不能在子类中修改。
You can revise the SurveyQuestion example from above to use
a constant property rather than a variable property for the text property of the question,
to indicate that the question doesn't change once an instance of SurveyQuestion is created.
Even though the text property is now a constant,
it can still be set within the class's initializer:
你可以修改上面的 SurveyQuestion 示例,将问题的 text 属性从变量属性改为常量属性,以表明一旦 SurveyQuestion 实例被创建,text 是不会改变的。即使 text 属性现在是一个常量,它仍然可以在类的构造器中被设置:
class SurveyQuestion {
let text: String
var response: String?
init(text: String) {
self.text = text
}
func ask() {
print(text)
}
}
let beetsQuestion = SurveyQuestion(text: "How about beets?")
beetsQuestion.ask()
// Prints "How about beets?"
beetsQuestion.response = "I also like beets. (But not with cheese.)"Default Initializers 默认构造器
Swift provides a default initializer for any structure or class that provides default values for all of its properties and doesn't provide at least one initializer itself. The default initializer simply creates a new instance with all of its properties set to their default values.
如果结构体或类为所有属性提供了默认值,又没有提供任何自定义的构造器,那么 Swift 会给这些结构体或类提供一个默认构造器。这个默认构造器将简单地创建一个所有属性值都设置为它们默认值的实例。
This example defines a class called ShoppingListItem,
which encapsulates the name, quantity, and purchase state
of an item in a shopping list:
下面例子中定义了一个类 ShoppingListItem,它封装了购物清单中的某一物品的名字(name)、数量(quantity)和购买状态 purchase state:
class ShoppingListItem {
var name: String?
var quantity = 1
var purchased = false
}
var item = ShoppingListItem()Because all properties of the ShoppingListItem class have default values,
and because it's a base class with no superclass,
ShoppingListItem automatically gains a default initializer implementation
that creates a new instance with all of its properties set to their default values.
(The name property is an optional String property,
and so it automatically receives a default value of nil,
even though this value isn't written in the code.)
The example above uses the default initializer for the ShoppingListItem class
to create a new instance of the class with initializer syntax,
written as ShoppingListItem(),
and assigns this new instance to a variable called item.
由于 ShoppingListItem 类的所有属性都有默认值,并且它是一个没有超类的基类。因此,ShoppingListItem 会自动获得一个默认构造器实现,该实现会创建一个新实例,并将其所有属性设置为默认值。(name 属性是一个可选的 String 属性,因此它会自动接收一个默认值 nil,即使这个值没有在代码中写出。)上面的示例使用 ShoppingListItem 类的默认构造器来创建一个类的新实例( ShoppingListItem()形式的构造语法),并将其赋值给变量 item 。
Memberwise Initializers for Structure Types 结构体逐一成员构造器
Structure types automatically receive a memberwise initializer if they don't define any of their own custom initializers. Unlike a default initializer, the structure receives a memberwise initializer even if it has stored properties that don't have default values.
如果结构体类型没有定义任何自定义构造器,它们会自动获得逐一成员构造器。与默认构造器不同,即使存储属性没有默认值,结构体也会获得逐一成员构造器。
The memberwise initializer is a shorthand way to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name.
成员逐一构造器是一种用于初始化新结构体实例里成员属性的快捷方法。新实例的属性的初始值可以通过名称传递给逐一成员构造器。
The example below defines a structure called Size
with two properties called width and height.
Both properties are inferred to be of type Double
by assigning a default value of 0.0.
下面的示例定义了一个名为 Size 的结构体,该结构体有两个属性,分别是 width 和 height。通过赋予默认值 0.0,这两个属性都被推断为 Double 类型。
The Size structure automatically receives an init(width:height:)
memberwise initializer,
which you can use to initialize a new Size instance:
Size 结构体会自动获得一个 init(width:height:) 逐一成员构造器,你可以用它来构造一个新的 Size 实例:
struct Size {
var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)When you call a memberwise initializer,
you can omit values for any properties
that have default values.
In the example above,
the Size structure has a default value
for both its height and width properties.
You can omit either property or both properties,
and the initializer uses the default value for anything you omit.
For example:
When you call a memberwise initializer,
you can omit values for any properties
that have default values.
In the example above,
the Size structure has a default value
for both its height and width properties.
You can omit either property or both properties,
and the initializer uses the default value for anything you omit.
For example:
当你调用逐一成员构造器时,你可以省略任何具有默认值的属性。在上面的示例中,Size 结构体的 height 和 width 属性都有默认值。你可以省略其中一个或两个属性,构造器会使用默认值。例如:
let zeroByTwo = Size(height: 2.0)
print(zeroByTwo.width, zeroByTwo.height)
// Prints "0.0 2.0".
let zeroByZero = Size()
print(zeroByZero.width, zeroByZero.height)
// Prints "0.0 0.0".Initializer Delegation for Value Types 值类型的构造器代理
Initializers can call other initializers to perform part of an instance's initialization. This process, known as initializer delegation, avoids duplicating code across multiple initializers.
构造器可以调用其他构造器来完成实例的部分构造过程。这个过程被称为构造器代理,它避免了在多个构造器中重复代码。
The rules for how initializer delegation works, and for what forms of delegation are allowed, are different for value types and class types. Value types (structures and enumerations) don't support inheritance, and so their initializer delegation process is relatively simple, because they can only delegate to another initializer that they provide themselves. Classes, however, can inherit from other classes, as described in Inheritance. This means that classes have additional responsibilities for ensuring that all stored properties they inherit are assigned a suitable value during initialization. These responsibilities are described in Class Inheritance and Initialization below.
For value types, you use self.init to refer to other initializers
from the same value type when writing your own custom initializers.
You can call self.init only from within an initializer.
对于值类型,你可以使用 self.init 在自定义的构造器中引用相同值类型的构造器。并且,你只能在构造器内部调用 self.init 。
Note that if you define a custom initializer for a value type, you will no longer have access to the default initializer (or the memberwise initializer, if it's a structure) for that type. This constraint prevents a situation in which additional essential setup provided in a more complex initializer is accidentally circumvented by someone using one of the automatic initializers.
请注意,如果你为某个值类型定义了一个自定义构造器,你将无法访问到默认构造器(如果是结构体,还将无法访问逐一成员构造器)。这种限制避免了在一个更复杂的构造器中做了额外的重要设置,但有人不小心使用自动生成的构造器而导致错误的情况。
Note · 注意
If you want your custom value type to be initializable with the default initializer and memberwise initializer, and also with your own custom initializers, write your custom initializers in an extension rather than as part of the value type's original implementation. For more information, see Extensions.
如果你希望默认构造器、逐一成员构造器以及你自己的自定义构造器都能用来创建实例,可以将自定义的构造器写到扩展(extension)中,而不是写在值类型的原始定义中。想查看更多内容,请查看扩展.
The following example defines a custom Rect structure to represent a geometric rectangle.
The example requires two supporting structures called Size and Point,
both of which provide default values of 0.0 for all of their properties:
下面的示例中定义了一个自定义结构体 Rect ,用来代表几何矩形。这个示例需要两个辅助的结构体 Size 和 Point ,它们各自为其所有的属性提供了默认值 0.0 .
struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}You can initialize the Rect structure below in one of three ways ---
by using its default zero-initialized origin and size property values,
by providing a specific origin point and size,
or by providing a specific center point and size.
These initialization options are represented by
three custom initializers that are part of the Rect structure's definition:
你可以通过三种方式为 Rect 创建实例 (1)使用含有默认值 origin 和 size 属性来初始化;(2)提供指定的 origin 和 size 实例来初始化;(3)提供指定的 center 和 size 来初始化。在下面 Rect 结构体定义中,我们为这三种方法提供了三个自定义的构造器:
struct Rect {
var origin = Point()
var size = Size()
init() {}
init(origin: Point, size: Size) {
self.origin = origin
self.size = size
}
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}The first Rect initializer, init(),
is functionally the same as the default initializer that the structure would have received
if it didn't have its own custom initializers.
This initializer has an empty body,
represented by an empty pair of curly braces {}.
Calling this initializer returns a Rect instance whose
origin and size properties are both initialized with
the default values of Point(x: 0.0, y: 0.0)
and Size(width: 0.0, height: 0.0)
from their property definitions:
第一个 Rect 构造器 init() ,在功能上跟没有自定义构造器时自动获得的默认构造器是一样的。这个构造器的函数是空的,使用一对大括号 {} 来表示。
调用这个构造器将返回一个 Rect 实例,它的origin 和 size 属性都使用定义时的默认值 Point(x: 0.0, y: 0.0) 和 Size(width: 0.0, height: 0.0) :
let basicRect = Rect()
// basicRect's origin is (0.0, 0.0) and its size is (0.0, 0.0)The second Rect initializer, init(origin:size:),
is functionally the same as the memberwise initializer that the structure would have received
if it didn't have its own custom initializers.
This initializer simply assigns the origin and size argument values to
the appropriate stored properties:
第二个 Rect 构造器 init(origin:size:) ,在功能上跟结构体在没有自定义构造器时获得的逐一成员构造器是一样的。这个构造器只是简单地将 origin 和 size 的实参值赋给对应的存储类型:
let originRect = Rect(origin: Point(x: 2.0, y: 2.0),
size: Size(width: 5.0, height: 5.0))
// originRect's origin is (2.0, 2.0) and its size is (5.0, 5.0)The third Rect initializer, init(center:size:), is slightly more complex.
It starts by calculating an appropriate origin point based on
a center point and a size value.
It then calls (or delegates) to the init(origin:size:) initializer,
which stores the new origin and size values in the appropriate properties:
第三个 Rect 构造器 init(center:size:) 要稍微更复杂一点。它先通过 center 和 size 的值计算出 origin 的坐标,然后再调用(或者说 代理 给) init(origin:size:) 构造器来将新的 origin 和 size 值赋值到对应的属性中:
let centerRect = Rect(center: Point(x: 4.0, y: 4.0),
size: Size(width: 3.0, height: 3.0))
// centerRect's origin is (2.5, 2.5) and its size is (3.0, 3.0)The init(center:size:) initializer could have assigned
the new values of origin and size to the appropriate properties itself.
However, it's more convenient (and clearer in intent)
for the init(center:size:) initializer to take advantage of an existing initializer
that already provides exactly that functionality.
构造器 init(center:size:) 本可以自己将 origin 和 size 的新值赋值到对应的属性中。然而,让构造器 init(center:size:) 利用一个恰好提供了该功能的现有构造器会更加便捷(而且意图更清晰)。
Note · 注意
For an alternative way to write this example without defining
the init() and init(origin:size:) initializers yourself,
see Extensions.
如果你想使用另一种不需要自己定义的 init() and init(origin:size:) 构造器的方式来实现这个例子, 请参考 扩展.
Class Inheritance and Initialization 类的继承和构造过程
All of a class's stored properties --- including any properties the class inherits from its superclass --- must be assigned an initial value during initialization.
类里面的所有存储型属性———包括所有继承自父类的属性——都必须在构造过程中设置初始值。
Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value. These are known as designated initializers and convenience initializers.
Swift 为类类型提供了两种构造器来确保实例中所有存储型属性都能获得初始值,它们被称为指定构造器和便利构造器。
Designated Initializers and Convenience Initializers 指定构造器和便利构造器
Designated initializers are the primary initializers for a class. A designated initializer fully initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain.
指定构造器 是类中最主要的构造器。一个指定构造器将初始化类中提供的所有属性,并调用合适的父类构造器让构造过程沿着父类链继续往上进行。
Classes tend to have very few designated initializers, and it's quite common for a class to have only one. Designated initializers are “funnel” points through which initialization takes place, and through which the initialization process continues up the superclass chain.
类倾向于拥有极少的指定构造器,普遍的是一个类只拥有一个指定构造器。指定构造器像一个个“漏斗”放在构造过程发生的地方,让构造过程沿着父类链继续往上进行。
Every class must have at least one designated initializer. In some cases, this requirement is satisfied by inheriting one or more designated initializers from a superclass, as described in Automatic Initializer Inheritance below.
每一个类都必须至少拥有一个指定构造器。在某些情况下,许多类通过继承了父类中的指定构造器而满足了这个条件。具体内容请参考后续章节构造器的自动继承。
Convenience initializers are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer's parameters set to default values. You can also define a convenience initializer to create an instance of that class for a specific use case or input value type.
便利构造器 是类中比较次要的、辅助型的构造器。你可以定义便利构造器来调用同一个类中的指定构造器,并为部分形参提供默认值。你也可以定义便利构造器来创建一个特殊用途或特定输入值的实例。
You don't have to provide convenience initializers if your class doesn't require them. Create convenience initializers whenever a shortcut to a common initialization pattern will save time or make initialization of the class clearer in intent.
你应当只在必要的时候为类提供便利构造器,比方说某种情况下通过使用便利构造器来快捷调用某个指定构造器,能够节省更多开发时间并让类的构造过程更清晰明了。
Syntax for Designated and Convenience Initializers 指定构造器和便利构造器的语法
Designated initializers for classes are written in the same way as simple initializers for value types:
类的指定构造器的写法跟值类型简单构造器一样:
init(<#parameters#>) {
<#statements#>
}Convenience initializers are written in the same style,
but with the convenience modifier placed before the init keyword,
separated by a space:
便利构造器也采用相同样式的写法,但需要在 init 关键字之前放置 convenience 关键字,并使用空格将其分开:
convenience init(<#parameters#>) {
<#statements#>
}Initializer Delegation for Class Types 类类型的构造器代理
To simplify the relationships between designated and convenience initializers, Swift applies the following three rules for delegation calls between initializers:
为了简化指定构造器和便利构造器之间的调用关系,Swift 构造器之间的代理调用遵循以下三条规则:
- term Rule 1: A designated initializer must call a designated initializer from its immediate superclass.
- term 规则 1: 指定构造器必须调用其直接父类的的指定构造器。
- term Rule 2: A convenience initializer must call another initializer from the same class.
- term 规则 2: 便利构造器必须调用 相同 类中定义的其它构造器.
- term Rule 3: A convenience initializer must ultimately call a designated initializer.
- term 规则 3: 便利构造器最后必须调用指定构造器。
A simple way to remember this is:
一个更方便记忆的方法是:
- Designated initializers must always delegate up.
- Convenience initializers must always delegate across.
- 指定构造器必须总是 向上 代理
- 便利构造器必须总是 横向 代理
These rules are illustrated in the figure below:
这些规则可以通过下面图例来说明:

Here, the superclass has a single designated initializer and two convenience initializers. One convenience initializer calls another convenience initializer, which in turn calls the single designated initializer. This satisfies rules 2 and 3 from above. The superclass doesn't itself have a further superclass, and so rule 1 doesn't apply.
如图所示,父类中包含一个指定构造器和两个便利构造器。其中一个便利构造器调用了另外一个便利构造器,而后者又调用了唯一的指定构造器。这满足了上面提到的规则 2 和 3。这个父类没有自己的父类,所以规则 1 没有用到。
The subclass in this figure has two designated initializers and one convenience initializer. The convenience initializer must call one of the two designated initializers, because it can only call another initializer from the same class. This satisfies rules 2 and 3 from above. Both designated initializers must call the single designated initializer from the superclass, to satisfy rule 1 from above.
子类中包含两个指定构造器和一个便利构造器。便利构造器必须调用两个指定构造器中的任意一个,因为它只能调用同一个类里的其他构造器。这满足了上面提到的规则 2 和 3。而两个指定构造器必须调用父类中唯一的指定构造器,这满足了规则 1。
Note · 注意
These rules don't affect how users of your classes create instances of each class. Any initializer in the diagram above can be used to create a fully initialized instance of the class they belong to. The rules only affect how you write the implementation of the class's initializers.
这些规则不会影响类的实例如何 创建 。任何上图中展示的构造器都可以用来创建完全初始化的实例。这些规则只影响类的构造器如何实现。
The figure below shows a more complex class hierarchy for four classes. It illustrates how the designated initializers in this hierarchy act as “funnel” points for class initialization, simplifying the interrelationships among classes in the chain:
下面图例中展示了一种涉及四个类的更复杂的类层级结构。它演示了指定构造器是如何在类层级中充当“漏斗”的作用,在类的构造器链上简化了类之间的相互关系。

Two-Phase Initialization 两段式构造过程
Class initialization in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.
Swift 中类的构造过程包含两个阶段。第一个阶段,类中的每个存储型属性赋一个初始值。当每个存储型属性的初始值被赋值后,第二阶段开始,它给每个类一次机会,在新实例准备使用之前进一步自定义它们的存储型属性。
The use of a two-phase initialization process makes initialization safe, while still giving complete flexibility to each class in a class hierarchy. Two-phase initialization prevents property values from being accessed before they're initialized, and prevents property values from being set to a different value by another initializer unexpectedly.
两段式构造过程的使用让构造过程更安全,同时在整个类层级结构中给予了每个类完全的灵活性。两段式构造过程可以防止属性值在初始化之前被访问,也可以防止属性被另外一个构造器意外地赋予不同的值。
Note · 注意
Swift's two-phase initialization process is similar to initialization in Objective-C.
The main difference is that during phase 1,
Objective-C assigns zero or null values (such as 0 or nil) to every property.
Swift's initialization flow is more flexible
in that it lets you set custom initial values,
and can cope with types for which 0 or nil isn't a valid default value.
Swift 的两段式构造过程跟 Objective-C 中的构造过程类似。最主要的区别在于阶段 1,Objective-C 给每一个属性赋值零或空值(比如说 0 或 nil)。
Swift 的构造流程则更加灵活,它允许你设置定制的初始值,并自如应对某些属性不能以 0 或 nil 作为合法默认值的情况。
Swift's compiler performs four helpful safety-checks to make sure that two-phase initialization is completed without error:
Swift 编译器将执行 4 种有效的安全检查,以确保两段式构造过程不出错地完成:
- term Safety check 1: A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.
- term 安全检查 1: 指定构造器必须保证它所在类的所有属性都初始化完成,之后才能将其它构造任务向上代理给父类中的构造器。
As mentioned above, the memory for an object is only considered fully initialized once the initial state of all of its stored properties is known. In order for this rule to be satisfied, a designated initializer must make sure that all of its own properties are initialized before it hands off up the chain.
如上所述,一个对象的内存只有在其所有存储型属性确定之后才能完全初始化。为了满足这一规则,指定构造器必须保证它所在类的属性在它往上代理之前先完成初始化。
- term Safety check 2: A designated initializer must delegate up to a superclass initializer before assigning a value to an inherited property. If it doesn't, the new value the designated initializer assigns will be overwritten by the superclass as part of its own initialization.
- term 安全检查 2: 指定构造器必须在为继承的属性设置新值之前向上代理调用父类构造器。如果没这么做,指定构造器赋予的新值将被父类中的构造器所覆盖。
- term Safety check 3: A convenience initializer must delegate to another initializer before assigning a value to any property (including properties defined by the same class). If it doesn't, the new value the convenience initializer assigns will be overwritten by its own class's designated initializer.
- term 安全检查 3: 便利构造器必须为任意属性(包括所有同类中定义的)赋新值之前代理调用其它构造器。如果没这么做,便利构造器赋予的新值将被该类的指定构造器所覆盖。
- term Safety check 4:
An initializer can't call any instance methods,
read the values of any instance properties,
or refer to
selfas a value until after the first phase of initialization is complete.
- term 安全检查 4:
构造器在第一阶段构造完成之前,不能调用任何实例方法,不能读取任何实例属性的值,不能引用
self作为一个值。
The class instance isn't fully valid until the first phase ends. Properties can only be accessed, and methods can only be called, once the class instance is known to be valid at the end of the first phase.
类的实例在第一阶段结束以前并不是完全有效的。只有第一阶段完成后,类的实例才是有效的,才能访问属性和调用方法。
Here's how two-phase initialization plays out, based on the four safety checks above:
以下是基于上述安全检查的两段式构造过程展示:
Phase 1
阶段 1
- A designated or convenience initializer is called on a class.
- Memory for a new instance of that class is allocated. The memory isn't yet initialized.
- A designated initializer for that class confirms that all stored properties introduced by that class have a value. The memory for these stored properties is now initialized.
- The designated initializer hands off to a superclass initializer to perform the same task for its own stored properties.
- This continues up the class inheritance chain until the top of the chain is reached.
- Once the top of the chain is reached, and the final class in the chain has ensured that all of its stored properties have a value, the instance's memory is considered to be fully initialized, and phase 1 is complete.
- 类的某个指定构造器或便利构造器被调用.
- 完成类的新实例内存的分配,但此时内存还没有被初始化.
- 指定构造器确保其所在类引入的所有存储型属性都已赋初值。存储型属性所属的内存完成初始化。
- 指定构造器切换到父类的构造器,对其存储属性完成相同的任务。
- 这个过程沿着类的继承链一直往上执行,直到到达继承链的最顶部。
- 当到达了继承链最顶部,而且继承链的最后一个类已确保所有的存储型属性都已经赋值,这个实例的内存被认为已经完全初始化。此时阶段 1 完成。
Phase 2
阶段 2
- Working back down from the top of the chain,
each designated initializer in the chain has the option to customize the instance further.
Initializers are now able to access
selfand can modify its properties, call its instance methods, and so on. - Finally, any convenience initializers in the chain have the option
to customize the instance and to work with
self.
- 从继承链顶部往下,继承链中每个类的指定构造器都有机会进一步自定义实例。构造器此时可以访问
self、修改它的属性并调用实例方法等等。 - 最终,继承链中任意的便利构造器有机会自定义实例和使用
self.
Here's how phase 1 looks for an initialization call for a hypothetical subclass and superclass:
下图展示了在假定的子类和父类之间的构造阶段 1:

In this example, initialization begins with a call to a convenience initializer on the subclass. This convenience initializer can't yet modify any properties. It delegates across to a designated initializer from the same class.
在这个示例中,构造过程从对子类中一个便利构造器的调用开始。这个便利构造器此时还不能修改任何属性,它会代理到该类中的指定构造器。
The designated initializer makes sure that all of the subclass's properties have a value, as per safety check 1. It then calls a designated initializer on its superclass to continue the initialization up the chain.
如安全检查 1 所示,指定构造器将确保所有子类的属性都有值。然后它将调用父类的指定构造器,并沿着继承链一直往上完成父类的构造过程。
The superclass's designated initializer makes sure that all of the superclass properties have a value. There are no further superclasses to initialize, and so no further delegation is needed.
父类中的指定构造器确保所有父类的属性都有值。由于没有更多的父类需要初始化,也就无需继续向上代理。
As soon as all properties of the superclass have an initial value, its memory is considered fully initialized, and phase 1 is complete.
一旦父类中所有属性都有了初始值,实例的内存被认为是完全初始化,阶段 1 完成。
Here's how phase 2 looks for the same initialization call:
以下展示了相同构造过程的阶段 2:

The superclass's designated initializer now has an opportunity to customize the instance further (although it doesn't have to).
父类中的指定构造器现在有机会进一步自定义实例(尽管这不是必须的)。
Once the superclass's designated initializer is finished, the subclass's designated initializer can perform additional customization (although again, it doesn't have to).
一旦父类中的指定构造器完成调用,子类中的指定构造器可以执行更多的自定义操作(这也不是必须的)。
Finally, once the subclass's designated initializer is finished, the convenience initializer that was originally called can perform additional customization.
最终,一旦子类的指定构造器完成调用,最开始被调用的便利构造器可以执行更多的自定义操作。
Initializer Inheritance and Overriding 构造器的继承和重写
Unlike subclasses in Objective-C, Swift subclasses don't inherit their superclass initializers by default. Swift's approach prevents a situation in which a simple initializer from a superclass is inherited by a more specialized subclass and is used to create a new instance of the subclass that isn't fully or correctly initialized.
跟 Objective-C 中的子类不同,Swift 中的子类默认情况下不会继承父类的构造器。Swift 的这种机制可以防止一个父类的简单构造器被一个更精细的子类继承,而在用来创建子类的新实例时没有完全或错误被初始化。
Note · 注意
Superclass initializers are inherited in certain circumstances, but only when it's safe and appropriate to do so. For more information, see Automatic Initializer Inheritance below.
父类的构造器仅会在安全和适当的某些情况下 被 继承。具体内容请参考后续章节 构造器的自动继承 .
If you want a custom subclass to present one or more of the same initializers as its superclass, you can provide a custom implementation of those initializers within the subclass.
假如你希望自定义的子类中能提供一个或多个跟父类相同的构造器,你可以在子类中提供这些构造器的自定义实现。
When you write a subclass initializer that matches a superclass designated initializer,
you are effectively providing an override of that designated initializer.
Therefore, you must write the override modifier before the subclass's initializer definition.
This is true even if you are overriding an automatically provided default initializer,
as described in Default Initializers.
当你在编写一个和父类中指定构造器相匹配的子类构造器时,你实际上是在重写父类的这个指定构造器。因此,你必须在定义子类构造器时带上 override 修饰符。即使你重写的是系统自动提供的默认构造器,也需要带上 override 修饰符,具体内容请参考默认构造器.
As with an overridden property, method or subscript,
the presence of the override modifier prompts Swift to check that
the superclass has a matching designated initializer to be overridden,
and validates that the parameters for your overriding initializer have been specified as intended.
正如重写属性,方法或者是下标,override 修饰符会让编译器去检查父类中是否有相匹配的指定构造器,并验证构造器参数是否按预想中被指定。
Note · 注意
You always write the override modifier when overriding a superclass designated initializer,
even if your subclass's implementation of the initializer is a convenience initializer.
当你重写一个父类的指定构造器时,你总是需要写 override 修饰符,即使是为了实现子类的便利构造器。
Conversely, if you write a subclass initializer that matches a superclass convenience initializer,
that superclass convenience initializer can never be called directly by your subclass,
as per the rules described above in Initializer Delegation for Class Types.
Therefore, your subclass is not (strictly speaking) providing an override of the superclass initializer.
As a result, you don't write the override modifier when providing
a matching implementation of a superclass convenience initializer.
相反,如果你编写了一个和父类便利构造器相匹配的子类构造器,由于子类不能直接调用父类的便利构造器(每个规则都在上文类类型的构造器代理有所描述)。
因此,严格意义上来讲,你的子类并未对一个父类构造器提供重写。最后的结果就是,你在子类中“重写”一个父类便利构造器时,不需要加 override 修饰符。
The example below defines a base class called Vehicle.
This base class declares a stored property called numberOfWheels,
with a default Int value of 0.
The numberOfWheels property is used by a computed property called description
to create a String description of the vehicle's characteristics:
在下面的例子中定义了一个叫 Vehicle 的基类。基类中声明了一个存储型属性 numberOfWheels ,它是默认值为 Int 类型的 0 。 numberOfWheels 属性用在一个描述车辆特征 String 类型为 description 的计算型属性中:
class Vehicle {
var numberOfWheels = 0
var description: String {
return "\(numberOfWheels) wheel(s)"
}
}The Vehicle class provides a default value for its only stored property,
and doesn't provide any custom initializers itself.
As a result, it automatically receives a default initializer,
as described in Default Initializers.
The default initializer (when available) is always a designated initializer for a class,
and can be used to create a new Vehicle instance with a numberOfWheels of 0:
Vehicle 类只为存储型属性提供默认值,也没有提供自定义构造器。因此,它会自动获得一个默认构造器,具体内容请参考默认构造器。默认构造器(如果有的话)总是类中的指定构造器,可以用于创建 numberOfWheels 为 0 的 Vehicle 实例:
let vehicle = Vehicle()
print("Vehicle: \(vehicle.description)")
// Vehicle: 0 wheel(s)The next example defines a subclass of Vehicle called Bicycle:
下面例子中定义了一个 Vehicle 的子类 Bicycle:
class Bicycle: Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}The Bicycle subclass defines a custom designated initializer, init().
This designated initializer matches a designated initializer from the superclass of Bicycle,
and so the Bicycle version of this initializer is marked with the override modifier.
子类 Bicycle 定义了一个自定义指定构造器 init()。这个指定构造器和父类的指定构造器相匹配,所以 Bicycle 中这个版本的构造器需要带上 override 修饰符。
The init() initializer for Bicycle starts by calling super.init(),
which calls the default initializer for the Bicycle class's superclass, Vehicle.
This ensures that the numberOfWheels inherited property is initialized by Vehicle
before Bicycle has the opportunity to modify the property.
After calling super.init(),
the original value of numberOfWheels is replaced with a new value of 2.
Bicycle 的构造器 init() 以调用 super.init() 方法开始,这个方法的作用是调用 Bicycle 的父类 Vehicle 的默认构造器。这样可以确保 Bicycle 在修改属性之前,它所继承的属性 numberOfWheels 能被 Vehicle 类初始化。在调用 super.init() 之后,属性 numberOfWheels 的原值被新值 2 替换。
If you create an instance of Bicycle,
you can call its inherited description computed property
to see how its numberOfWheels property has been updated:
如果你创建一个 Bicycle 实例, 你可以调用继承的 description 计算型属性去查看属性 numberOfWheels 是否有改变:
let bicycle = Bicycle()
print("Bicycle: \(bicycle.description)")
// Bicycle: 2 wheel(s)If a subclass initializer performs no customization
in phase 2 of the initialization process,
and the superclass has a synchronous, zero-argument designated initializer,
you can omit a call to super.init()
after assigning values to all of the subclass's stored properties.
If the superclass's initializer is asynchronous,
you need to write await super.init() explicitly.
如果子类的构造器没有在阶段 2 过程中做自定义操作,并且父类有一个同步、无参数的指定构造器,你可以在所有子类的存储属性赋值之后省略 super.init() 的调用。若父类的构造器是异步的,你就需要明确地写入 await super.init() 。
This example defines another subclass of Vehicle, called Hoverboard.
In its initializer, the Hoverboard class sets only its color property.
Instead of making an explicit call to super.init(),
this initializer relies on an implicit call to its superclass's initializer
to complete the process.
这个例子定义了另一个 Vehicle 的子类 Hoverboard ,只设置它的 color 属性。这个构造器依赖隐式调用父类的构造器来完成,而不是显式调用 super.init() 。
class Hoverboard: Vehicle {
var color: String
init(color: String) {
self.color = color
// super.init() implicitly called here
}
override var description: String {
return "\(super.description) in a beautiful \(color)"
}
}An instance of Hoverboard uses the default number of wheels
supplied by the Vehicle initializer.
Hoverboard 的实例用 Vehicle 构造器里默认的轮子数量。
let hoverboard = Hoverboard(color: "silver")
print("Hoverboard: \(hoverboard.description)")
// Hoverboard: 0 wheel(s) in a beautiful silverNote · 注意
Subclasses can modify inherited variable properties during initialization, but can't modify inherited constant properties.
子类可以在构造过程修改继承来的变量属性,但是不能修改继承来的常量属性。
Automatic Initializer Inheritance 构造器的自动继承
As mentioned above, subclasses don't inherit their superclass initializers by default. However, superclass initializers are automatically inherited if certain conditions are met. In practice, this means that you don't need to write initializer overrides in many common scenarios, and can inherit your superclass initializers with minimal effort whenever it's safe to do so.
如上所述,子类在默认情况下不会继承父类的构造器。但是如果满足特定条件,父类构造器是可以 被 自动继承的。事实上,这意味着对于许多常见场景你不必重写父类的构造器,并且可以在安全的情况下以最小的代价继承父类的构造器。
Assuming that you provide default values for any new properties you introduce in a subclass, the following two rules apply:
假设你为子类中引入的所有新属性都提供了默认值,以下 2 个规则将适用:
- term Rule 1: If your subclass doesn't define any designated initializers, it automatically inherits all of its superclass designated initializers.
- term 规则 1*: 如果子类没有定义任何指定构造器,它将自动继承父类所有的指定构造器。
- term Rule 2: If your subclass provides an implementation of all of its superclass designated initializers --- either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition --- then it automatically inherits all of the superclass convenience initializers.
- term 规则 2: 如果子类提供了 所有 父类指定构造器的实现——无论是通过规则 1 继承过来的,还是提供了自定义实现——它将自动继承父类所有的便利构造器。
These rules apply even if your subclass adds further convenience initializers.
即使你在子类中添加了更多的便利构造器,这两条规则仍然适用。
Note · 注意
A subclass can implement a superclass designated initializer as a subclass convenience initializer as part of satisfying rule 2.
子类可以将父类的指定构造器实现为便利构造器来满足规则 2。
Designated and Convenience Initializers in Action 指定构造器和便利构造器实践
The following example shows designated initializers, convenience initializers,
and automatic initializer inheritance in action.
This example defines a hierarchy of three classes called
Food, RecipeIngredient, and ShoppingListItem,
and demonstrates how their initializers interact.
接下来的例子将在实践中展示指定构造器、便利构造器以及构造器的自动继承。这个例子定义了包含三个类 Food, RecipeIngredient, 以及 ShoppingListItem 的层级结构,并将演示它们的构造器是如何相互作用的。
The base class in the hierarchy is called Food,
which is a simple class to encapsulate the name of a foodstuff.
The Food class introduces a single String property called name
and provides two initializers for creating Food instances:
类层次中的基类是 Food ,它是一个简单的用来封装食物名字的类。 Food 类引入了一个叫做 name 的 String 类型的属性,并且提供了两个构造器来创建 Food 实例:
class Food {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "[Unnamed]")
}
}The figure below shows the initializer chain for the Food class:
下图展示了 Food 的构造链路:

Classes don't have a default memberwise initializer,
and so the Food class provides a designated initializer
that takes a single argument called name.
This initializer can be used to create a new Food instance with a specific name:
类类型没有默认的逐一成员构造器,所以 Food 类提供了一个接受单一参数 name 的指定构造器。这个构造器可以使用一个特定的名字来创建新的 Food 实例:
let namedMeat = Food(name: "Bacon")
// namedMeat's name is "Bacon"The init(name: String) initializer from the Food class
is provided as a designated initializer,
because it ensures that all stored properties of
a new Food instance are fully initialized.
The Food class doesn't have a superclass,
and so the init(name: String) initializer doesn't need to call super.init()
to complete its initialization.
Food 类中的构造器 init(name: String) 被定义为一个 指定 构造器,因为它能确保 Food 实例的所有存储型属性都被初始化。 Food 类没有父类,所以 init(name: String) 构造器不需要调用 super.init() 来完成构造过程。
The Food class also provides a convenience initializer, init(), with no arguments.
The init() initializer provides a default placeholder name for a new food
by delegating across to the Food class's init(name: String) with
a name value of [Unnamed]:
Food 类样提供了一个没有参数的便利构造器 init() 。这个 init() 构造器为新食物提供了一个默认的占位名字,通过横向代理到指定构造器 init(name: String) 并给参数 name 赋值为 [Unnamed] 来实现:
let mysteryMeat = Food()
// mysteryMeat's name is "[Unnamed]"The second class in the hierarchy is a subclass of Food called RecipeIngredient.
The RecipeIngredient class models an ingredient in a cooking recipe.
It introduces an Int property called quantity
(in addition to the name property it inherits from Food)
and defines two initializers for creating RecipeIngredient instances:
层级中的第二个类是 Food 的子类 RecipeIngredient 。 RecipeIngredient 类用来表示食谱中的一项原料。它引入了 Int 类型的属性 quantity (以及从 Food 继承过来的 name 属性),并且定义了两个构造器来创建 RecipeIngredient 实例:
class RecipeIngredient: Food {
var quantity: Int
init(name: String, quantity: Int) {
self.quantity = quantity
super.init(name: name)
}
override convenience init(name: String) {
self.init(name: name, quantity: 1)
}
}The figure below shows the initializer chain for the RecipeIngredient class:
下图中展示了 RecipeIngredient 类的构造器链:

The RecipeIngredient class has a single designated initializer,
init(name: String, quantity: Int),
which can be used to populate all of the properties of a new RecipeIngredient instance.
This initializer starts by assigning
the passed quantity argument to the quantity property,
which is the only new property introduced by RecipeIngredient.
After doing so, the initializer delegates up to
the init(name: String) initializer of the Food class.
This process satisfies safety check 1
from Two-Phase Initialization above.
RecipeIngredient 类拥有一个指定构造器 init(name: String, quantity: Int), 它可以用来填充 RecipeIngredient 的所有属性值。 这个构造器一开始先将传入的 quantity 实参赋值给 quantity 属性,这个属性也是唯一在 RecipeIngredient 中新引入的属性。随后,构造器向上代理到父类 Food 的 init(name: String) 。这个过程满足 两段式构造过程 中的安全检查 1。
RecipeIngredient also defines a convenience initializer, init(name: String),
which is used to create a RecipeIngredient instance by name alone.
This convenience initializer assumes a quantity of 1
for any RecipeIngredient instance that's created without an explicit quantity.
The definition of this convenience initializer makes
RecipeIngredient instances quicker and more convenient to create,
and avoids code duplication when creating
several single-quantity RecipeIngredient instances.
This convenience initializer simply delegates across to the class's designated initializer,
passing in a quantity value of 1.
RecipeIngredient 也定义了一个便利构造器 init(name: String) ,它只通过 name 来创建 RecipeIngredient 的实例。这个便利构造器假设任意 RecipeIngredient 实例的 quantity 为 1 ,所以不需要显式的质量即可创建出实例。这个便利构造器的定义可以更加方便和快捷地创建实例,并且避免了创建多个 quantity 为 1 的 RecipeIngredient 实例时的代码重复。这个便利构造器只是简单地横向代理到类中的指定构造器,并为 quantity 参数传递 1 。
The init(name: String) convenience initializer provided by RecipeIngredient
takes the same parameters as the init(name: String) designated initializer from Food.
Because this convenience initializer overrides a designated initializer from its superclass,
it must be marked with the override modifier
(as described in Initializer Inheritance and Overriding).
RecipeIngredient 的便利构造器 init(name: String) 使用了跟 Food 中指定构造器 init(name: String) 相同的形参。由于这个便利构造器重写了父类的指定构造器 init(name: String) , 因此必须在前面使用 override 修饰符(参见构造器的继承和重写)
Even though RecipeIngredient provides
the init(name: String) initializer as a convenience initializer,
RecipeIngredient has nonetheless provided an implementation of
all of its superclass's designated initializers.
Therefore, RecipeIngredient automatically inherits
all of its superclass's convenience initializers too.
尽管 RecipeIngredient 将 init(name: String) 构造器作为便利构造器来提供,但 RecipeIngredient 依然提供了父类所有指定构造器的实现。因此,RecipeIngredient 也会自动继承父类的所有便利构造器。
In this example, the superclass for RecipeIngredient is Food,
which has a single convenience initializer called init().
This initializer is therefore inherited by RecipeIngredient.
The inherited version of init() functions in exactly the same way as the Food version,
except that it delegates to the RecipeIngredient version of init(name: String)
rather than the Food version.
在这个示例中, RecipeIngredient 的父类是 Food,它有一个便利构造器 init()。这个便利构造器会被 RecipeIngredient 继承。这个继承版本的 init() 在功能上跟 Food 提供的版本是一样的,只是它会代理到 RecipeIngredient 版本的 init(name: String) 而不是 Food 提供的版本.
All three of these initializers can be used to create new RecipeIngredient instances:
所有的这三种构造器都可以用来创建新的 RecipeIngredient 实例:
let oneMysteryItem = RecipeIngredient()
let oneBacon = RecipeIngredient(name: "Bacon")
let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6)The third and final class in the hierarchy is
a subclass of RecipeIngredient called ShoppingListItem.
The ShoppingListItem class models a recipe ingredient as it appears in a shopping list.
类层级中第三个也是最后一个类 ShoppingListItem 是 RecipeIngredient 的子类。它构建了购物单中出现的某一种食谱原料。
Every item in the shopping list starts out as “unpurchased”.
To represent this fact,
ShoppingListItem introduces a Boolean property called purchased,
with a default value of false.
ShoppingListItem also adds a computed description property,
which provides a textual description of a ShoppingListItem instance:
购物单中的每一项总是从未购买状态开始的。为了呈现这一事实, ShoppingListItem 引入了一个 Boolean(布尔类型)的属性 purchased ,它的默认值是 false 。 ShoppingListItem 还添加了一个计算型属性 description , 它提供了关于 ShoppingListItem 实例的一些文字描述:
class ShoppingListItem: RecipeIngredient {
var purchased = false
var description: String {
var output = "\(quantity) x \(name)"
output += purchased ? " ✔" : " ✘"
return output
}
}Note · 注意
ShoppingListItem doesn't define an initializer to provide
an initial value for purchased,
because items in a shopping list (as modeled here) always start out unpurchased.
ShoppingListItem 没有定义构造器来为 purchased 提供初始值,因为添加到购物单的物品的初始状态总是未购买。
Because it provides a default value for all of the properties it introduces
and doesn't define any initializers itself,
ShoppingListItem automatically inherits
all of the designated and convenience initializers from its superclass.
因为它为自己引入的所有属性都提供了默认值,并且自己没有定义任何构造器, ShoppingListItem 将自动继承 所有 父类中的指定构造器和便利构造器。
The figure below shows the overall initializer chain for all three classes:
下图展示了这三个类的构造器链:

You can use all three of the inherited initializers
to create a new ShoppingListItem instance:
你可以使用三个继承来的构造器来创建 ShoppingListItem 的新实例:
var breakfastList = [
ShoppingListItem(),
ShoppingListItem(name: "Bacon"),
ShoppingListItem(name: "Eggs", quantity: 6),
]
breakfastList[0].name = "Orange juice"
breakfastList[0].purchased = true
for item in breakfastList {
print(item.description)
}
// 1 x Orange juice ✔
// 1 x Bacon ✘
// 6 x Eggs ✘Here, a new array called breakfastList is created from
an array literal containing three new ShoppingListItem instances.
The type of the array is inferred to be [ShoppingListItem].
After the array is created,
the name of the ShoppingListItem at the start of the array
is changed from "[Unnamed]" to "Orange juice"
and it's marked as having been purchased.
Printing the description of each item in the array
shows that their default states have been set as expected.
如上所述,例子中通过字面量方式创建了一个数组 breakfastList ,它包含了三个 ShoppingListItem 实例,因此数组的类型也能被自动推导为 [ShoppingListItem] 。 在数组创建完之后,数组中第一个 ShoppingListItem 实例的名字从 "[Unnamed]" 更改为 "Orange juice" ,并标记状态为已购买。打印数组中每个元素的描述显示了它们都已按照预期被赋值。
Failable Initializers 可失败构造器
It's sometimes useful to define a class, structure, or enumeration for which initialization can fail. This failure might be triggered by invalid initialization parameter values, the absence of a required external resource, or some other condition that prevents initialization from succeeding.
有时,定义一个构造器可失败的类,结构体或者枚举是很有用的。这里的“失败” 指的是,如给构造器传入无效的形参,或缺少某种所需的外部资源,又或是不满足某种必要的条件等。
To cope with initialization conditions that can fail,
define one or more failable initializers as part of
a class, structure, or enumeration definition.
You write a failable initializer
by placing a question mark after the init keyword (init?).
为了妥善处理这种构造过程中可能会失败的情况。你可以在一个类,结构体或是枚举类型的定义中,添加一个或多个可失败构造器。其语法为在 init 关键字后面添加问号 (init?) 。
Note · 注意
You can't define a failable and a nonfailable initializer with the same parameter types and names.
可失败构造器的参数名和参数类型,不能与其它非可失败构造器的参数名,及其参数类型相同。
A failable initializer creates an optional value of the type it initializes.
You write return nil within a failable initializer
to indicate a point at which initialization failure can be triggered.
可失败构造器会创建一个类型为自身类型的 可选 类型的对象。你通过 return nil 语句来表明可失败构造器在何种情况下应该 “失败”。
Note · 注意
Strictly speaking, initializers don't return a value.
Rather, their role is to ensure that self is fully and correctly initialized
by the time that initialization ends.
Although you write return nil to trigger an initialization failure,
you don't use the return keyword to indicate initialization success.
严格来说,构造器并不返回值。构造器的作用是确保在构造过程结束时,self 已被完整且正确地初始化。因此,虽然你可以用 return nil 来触发构造失败,但不要用 return 关键字来表示构造成功。
For instance, failable initializers are implemented for numeric type conversions.
To ensure conversion between numeric types maintains the value exactly,
use the init(exactly:) initializer.
If the type conversion can't maintain the value,
the initializer fails.
例如,实现针对数字类型转换的可失败构造器。确保数字类型之间的转换能保持精确的值,使用这个 init(exactly:) 构造器。如果类型转换不能保持值不变,则这个构造器构造失败。
let wholeNumber: Double = 12345.0
let pi = 3.14159
if let valueMaintained = Int(exactly: wholeNumber) {
print("\(wholeNumber) conversion to Int maintains value of \(valueMaintained)")
}
// Prints "12345.0 conversion to Int maintains value of 12345".
let valueChanged = Int(exactly: pi)
// valueChanged is of type Int?, not Int
if valueChanged == nil {
print("\(pi) conversion to Int doesn't maintain value")
}
// Prints "3.14159 conversion to Int doesn't maintain value".The example below defines a structure called Animal,
with a constant String property called species.
The Animal structure also defines a failable initializer
with a single parameter called species.
This initializer checks if the species value passed to the initializer is an empty string.
If an empty string is found, an initialization failure is triggered.
Otherwise, the species property's value is set, and initialization succeeds:
下面示例中,定义一个名为 Animal 的结构体,其中有一个名为 species 的 String 类型的常量属性。同时该结构体还定义了一个接受一个名为 species 的 String 类型形参的可失败构造器。这个可失败构造器检查传入的 species 值是否为一个空字符串。如果为空字符串,则构造失败。否则, species 属性被赋值,构造成功。
struct Animal {
let species: String
init?(species: String) {
if species.isEmpty { return nil }
self.species = species
}
}You can use this failable initializer to try to initialize a new Animal instance
and to check if initialization succeeded:
你可以通过该可失败构造器来尝试构建一个 Animal 的实例,并检查构造过程是否成功:
let someCreature = Animal(species: "Giraffe")
// someCreature is of type Animal?, not Animal
if let giraffe = someCreature {
print("An animal was initialized with a species of \(giraffe.species)")
}
// Prints "An animal was initialized with a species of Giraffe".If you pass an empty string value to the failable initializer's species parameter,
the initializer triggers an initialization failure:
如果你给该可失败构造器传入一个空字符串到形参 species ,则会导致构造失败:
let anonymousCreature = Animal(species: "")
// anonymousCreature is of type Animal?, not Animal
if anonymousCreature == nil {
print("The anonymous creature couldn't be initialized")
}
// Prints "The anonymous creature couldn't be initialized".Note · 注意
Checking for an empty string value (such as "" rather than "Giraffe")
isn't the same as checking for nil to indicate the absence of an optional String value.
In the example above, an empty string ("") is a valid, non-optional String.
However, it's not appropriate for an animal
to have an empty string as the value of its species property.
To model this restriction,
the failable initializer triggers an initialization failure if an empty string is found.
检查空字符串的值 (如 "" 而不是 "Giraffe") 不等同于检查 nil 以表示 可选 String 值的缺失。
上述示例中的空字符串 ("") 是一个合法且非可选的 String.
然而, 对于 Animal 这个类来说,其 species 属性的值为空字符串是不合适的。
为了体现这个限制,如果发现使用空字符串,构造器就会触发初始化失败的错误。
Failable Initializers for Enumerations 枚举类型的可失败构造器
You can use a failable initializer to select an appropriate enumeration case based on one or more parameters. The initializer can then fail if the provided parameters don't match an appropriate enumeration case.
你可以通过一个基于一个或多个形参的可失败构造器来获取枚举类型中特定的枚举成员。如果提供的形参无法匹配任何枚举成员,则构造失败。
The example below defines an enumeration called TemperatureUnit,
with three possible states (kelvin, celsius, and fahrenheit).
A failable initializer is used to find an appropriate enumeration case
for a Character value representing a temperature symbol:
下面的示例中,定义了一个 TemperatureUnit 的枚举类型。其中包含了三个可能的枚举状态 (kelvin, celsius, and fahrenheit),以及一个根据表示温度单位的 Character 值找出合适的枚举成员的可失败构造器:
enum TemperatureUnit {
case kelvin, celsius, fahrenheit
init?(symbol: Character) {
switch symbol {
case "K":
self = .kelvin
case "C":
self = .celsius
case "F":
self = .fahrenheit
default:
return nil
}
}
}You can use this failable initializer to choose an appropriate enumeration case for the three possible states and to cause initialization to fail if the parameter doesn't match one of these states:
你可以利用该可失败构造器在三个枚举成员中选择合适的枚举成员,当形参不能和任何枚举成员相匹配时,则构造失败:
let fahrenheitUnit = TemperatureUnit(symbol: "F")
if fahrenheitUnit != nil {
print("This is a defined temperature unit, so initialization succeeded.")
}
// Prints "This is a defined temperature unit, so initialization succeeded."
let unknownUnit = TemperatureUnit(symbol: "X")
if unknownUnit == nil {
print("This isn't a defined temperature unit, so initialization failed.")
}
// Prints "This isn't a defined temperature unit, so initialization failed."Failable Initializers for Enumerations with Raw Values 带原始值的枚举类型的可失败构造器
Enumerations with raw values automatically receive a failable initializer,
init?(rawValue:),
that takes a parameter called rawValue of the appropriate raw-value type
and selects a matching enumeration case if one is found,
or triggers an initialization failure if no matching value exists.
带原始值的枚举类型会自带一个可失败构造器 init?(rawValue:) ,该可失败构造器有一个合适的原始值类型的 rawValue 形参,选择找到的相匹配的枚举成员,找不到则构造失败。
You can rewrite the TemperatureUnit example from above
to use raw values of type Character
and to take advantage of the init?(rawValue:) initializer:
因此 TemperatureUnit 的例子可以用原始值类型的 Character 和进阶的 init?(rawValue:) 构造器重写为:
enum TemperatureUnit: Character {
case kelvin = "K", celsius = "C", fahrenheit = "F"
}
let fahrenheitUnit = TemperatureUnit(rawValue: "F")
if fahrenheitUnit != nil {
print("This is a defined temperature unit, so initialization succeeded.")
}
// Prints "This is a defined temperature unit, so initialization succeeded."
let unknownUnit = TemperatureUnit(rawValue: "X")
if unknownUnit == nil {
print("This isn't a defined temperature unit, so initialization failed.")
}
// Prints "This isn't a defined temperature unit, so initialization failed."Propagation of Initialization Failure 构造失败的传递
A failable initializer of a class, structure, or enumeration can delegate across to another failable initializer from the same class, structure, or enumeration. Similarly, a subclass failable initializer can delegate up to a superclass failable initializer.
类、结构体、枚举的可失败构造器可以横向代理到它们自己其他的可失败构造器。类似的,子类的可失败构造器也能向上代理到父类的可失败构造器。
In either case, if you delegate to another initializer that causes initialization to fail, the entire initialization process fails immediately, and no further initialization code is executed.
无论是向上代理还是横向代理,如果你代理到的其他可失败构造器触发构造失败,整个构造过程将立即终止,接下来的任何构造代码不会再被执行。
Note · 注意
A failable initializer can also delegate to a nonfailable initializer. Use this approach if you need to add a potential failure state to an existing initialization process that doesn't otherwise fail.
可失败构造器也可以代理到其它的不可失败构造器。通过这种方式,你可以增加一个可能的失败状态到现有的构造过程中。
The example below defines a subclass of Product called CartItem.
The CartItem class models an item in an online shopping cart.
CartItem introduces a stored constant property called quantity
and ensures that this property always has a value of at least 1:
下面这个示例中定义了一个 Product 的子类 CartItem 。 CartItem 类建立了一个在线购物车中的物品的模型,它有一个名为 quantity 的常量存储型属性,并确保给属性的值至少为 1 :
class Product {
let name: String
init?(name: String) {
if name.isEmpty { return nil }
self.name = name
}
}
class CartItem: Product {
let quantity: Int
init?(name: String, quantity: Int) {
if quantity < 1 { return nil }
self.quantity = quantity
super.init(name: name)
}
}The failable initializer for CartItem starts by
validating that it has received a quantity value of 1 or more.
If the quantity is invalid,
the entire initialization process fails immediately
and no further initialization code is executed.
Likewise, the failable initializer for Product
checks the name value,
and the initializer process fails immediately
if name is the empty string.
CartItem 可失败构造器首先验证接收的 quantity 值是否大于等于1。倘若 quantity 值无效,则立即终止整个构造过程,返回失败结果,且不再执行余下代码。同样地, Product 的可失败构造器首先检查 name 值, 如果 name 值为空字符串,则构造器立即执行失败。
If you create a CartItem instance with a nonempty name and a quantity of 1 or more,
initialization succeeds:
如果你通过传入一个非空的 name 以及 大于等于 1 的 quantity 来创建一个 CartItem 实例,构建方法将成功执行:
if let twoSocks = CartItem(name: "sock", quantity: 2) {
print("Item: \(twoSocks.name), quantity: \(twoSocks.quantity)")
}
// Prints "Item: sock, quantity: 2".If you try to create a CartItem instance with a quantity value of 0,
the CartItem initializer causes initialization to fail:
如果你用值为 0 的 quantity 来创建一个 CartItem 实例,那么将导致 CartItem 的构造器失败:
if let zeroShirts = CartItem(name: "shirt", quantity: 0) {
print("Item: \(zeroShirts.name), quantity: \(zeroShirts.quantity)")
} else {
print("Unable to initialize zero shirts")
}
// Prints "Unable to initialize zero shirts".Similarly, if you try to create a CartItem instance with an empty name value,
the superclass Product initializer causes initialization to fail:
同样地,如果你尝试传入一个值为空字符串的 name 来创建一个 CartItem 实例,那么将导致父类 Product 的构造过程失败:
if let oneUnnamed = CartItem(name: "", quantity: 1) {
print("Item: \(oneUnnamed.name), quantity: \(oneUnnamed.quantity)")
} else {
print("Unable to initialize one unnamed product")
}
// Prints "Unable to initialize one unnamed product".Overriding a Failable Initializer 重写一个可失败构造器
You can override a superclass failable initializer in a subclass, just like any other initializer. Alternatively, you can override a superclass failable initializer with a subclass nonfailable initializer. This enables you to define a subclass for which initialization can't fail, even though initialization of the superclass is allowed to fail.
如同其它的构造器,你可以在子类中重写父类的可失败构造器。或者你也可以用子类的非可失败构造器重写一个父类的可失败构造器。这使你可以定义一个不会构造失败的子类,即使父类的构造器允许构造失败。
Note that if you override a failable superclass initializer with a nonfailable subclass initializer, the only way to delegate up to the superclass initializer is to force-unwrap the result of the failable superclass initializer.
注意,当你用子类的非可失败构造器重写父类的可失败构造器时,向上代理到父类的可失败构造器的唯一方式是对父类的可失败构造器的返回值进行强制解包。
Note · 注意
You can override a failable initializer with a nonfailable initializer but not the other way around.
你可以用非可失败构造器重写可失败构造器,但反过来却不行。
The example below defines a class called Document.
This class models a document that can be initialized with
a name property that's either a nonempty string value or nil,
but can't be an empty string:
下面的示例定义了 Document 类。这个类模拟一个文档并可以用 name 属性来构造,属性的值必须为一个非空的字符串或 nil ,但不能是一个空字符串:
class Document {
var name: String?
// this initializer creates a document with a nil name value
init() {}
// this initializer creates a document with a nonempty name value
init?(name: String) {
if name.isEmpty { return nil }
self.name = name
}
}The next example defines a subclass of Document called AutomaticallyNamedDocument.
The AutomaticallyNamedDocument subclass overrides
both of the designated initializers introduced by Document.
These overrides ensure that an AutomaticallyNamedDocument instance has
an initial name value of "[Untitled]"
if the instance is initialized without a name,
or if an empty string is passed to the init(name:) initializer:
下一个示例中定义了一个 Document 的子类 AutomaticallyNamedDocument 。 AutomaticallyNamedDocument 子类重写了所有父类引入的指定构造器。这些重写确保了 AutomaticallyNamedDocument 在没有 name 值时传递空字符串给 init(name:) 构造器,具有初始 name 值 "[Untitled]" 。
class AutomaticallyNamedDocument: Document {
override init() {
super.init()
self.name = "[Untitled]"
}
override init(name: String) {
super.init()
if name.isEmpty {
self.name = "[Untitled]"
} else {
self.name = name
}
}
}The AutomaticallyNamedDocument overrides its superclass's
failable init?(name:) initializer with a nonfailable init(name:) initializer.
Because AutomaticallyNamedDocument copes with the empty string case
in a different way than its superclass,
its initializer doesn't need to fail,
and so it provides a nonfailable version of the initializer instead.
AutomaticallyNamedDocument 用一个不可失败构造器 init(name:) 重写了父类的可失败构造器 init?(name:)。因为 AutomaticallyNamedDocument 用与父类不同的方式处理了空字符串的情况,所以它的构造器不需要失败,因此它提供了一个不可失败版本的构造器。
You can use forced unwrapping in an initializer
to call a failable initializer from the superclass
as part of the implementation of a subclass's nonfailable initializer.
For example, the UntitledDocument subclass below is always named "[Untitled]",
and it uses the failable init(name:) initializer
from its superclass during initialization.
你可以在子类的不可失败构造器中使用强制解包来调用父类的可失败构造器。比如,下面的 UntitledDocument 子类总是被命名为 "[Untitled]" 并且在初始化阶段使用父类的可失败构造器 init(name:) 。
class UntitledDocument: Document {
override init() {
super.init(name: "[Untitled]")!
}
}In this case, if the init(name:) initializer of the superclass
were ever called with an empty string as the name,
the forced unwrapping operation would result in a runtime error.
However, because it's called with a string literal,
you can see that the initializer won't fail,
so no runtime error can occur in this case.
在这个例子中,如果在调用父类的可失败构造器 init(name:) 时传入的是空字符串,那么强制解包操作会引发运行时错误。不过,因为这里是通过字符串字面量来调用它,构造器不会失败,所以在这个例子中并不会发生运行时错误。
The init! Failable Initializer init! 可失败构造器
You typically define a failable initializer
that creates an optional instance of the appropriate type
by placing a question mark after the init keyword (init?).
Alternatively, you can define a failable initializer that creates
an implicitly unwrapped optional instance of the appropriate type.
Do this by placing an exclamation point after the init keyword (init!)
instead of a question mark.
通常来说我们通过在 init 关键字后添加问号的方式 (init?) 来定义一个可失败的构造器。但你也可以通过在 init 后面添加感叹号的方式来定义一个可失败构造器 (init!) ,该可失败构造器将会构建一个对应类型的隐式解包可选类型的对象。
You can delegate from init? to init! and vice versa,
and you can override init? with init! and vice versa.
You can also delegate from init to init!,
although doing so will trigger an assertion
if the init! initializer causes initialization to fail.
你可以在 init? 中代理到 init! ,反之亦然。你也可以用 init? 重写 init! ,反之亦然。你还可以用 init 代理到 init! ,不过,一旦 init! 构造失败,则会触发断言。
Required Initializers 必要构造器
Write the required modifier before the definition of a class initializer
to indicate that every subclass of the class must implement that initializer:
在类的构造器前添加 required 修饰符表明所有该类的子类都必须实现该构造器:
class SomeClass {
required init() {
// initializer implementation goes here
}
}You must also write the required modifier before
every subclass implementation of a required initializer,
to indicate that the initializer requirement applies to further subclasses in the chain.
You don't write the override modifier when overriding a required designated initializer:
在子类重写父类的必要构造器时,必须在子类的构造器前也添加 required 修饰符,表明该构造器要求也应用于继承链后面的子类。在重写父类中必要的指定构造器时,不需要添加 override 修饰符:
class SomeSubclass: SomeClass {
required init() {
// subclass implementation of the required initializer goes here
}
}Note · 注意
You don't have to provide an explicit implementation of a required initializer if you can satisfy the requirement with an inherited initializer.
如果子类继承的构造器能满足必要构造器的要求,则无须在子类中显式提供必要构造器的实现。
Setting a Default Property Value with a Closure or Function 通过闭包或函数设置属性的默认值
If a stored property's default value requires some customization or setup, you can use a closure or global function to provide a customized default value for that property. Whenever a new instance of the type that the property belongs to is initialized, the closure or function is called, and its return value is assigned as the property's default value.
如果某个存储型属性的默认值需要一些自定义或设置,你可以使用闭包或全局函数为其提供定制的默认值。每当某个属性所在类型的新实例被构造时,对应的闭包或函数会被调用,而它们的返回值会当做默认值赋值给这个属性。
These kinds of closures or functions typically create a temporary value of the same type as the property, tailor that value to represent the desired initial state, and then return that temporary value to be used as the property's default value.
这种类型的闭包或函数通常会创建一个跟属性类型相同的临时变量,然后修改它的值以满足预期的初始状态,最后返回这个临时变量,作为属性的默认值。
Here's a skeleton outline of how a closure can be used to provide a default property value:
下面模板介绍了如何用闭包为属性提供默认值:
class SomeClass {
let someProperty: SomeType = {
// create a default value for someProperty inside this closure
// someValue must be of the same type as SomeType
return someValue
}()
}Note that the closure's end curly brace is followed by an empty pair of parentheses. This tells Swift to execute the closure immediately. If you omit these parentheses, you are trying to assign the closure itself to the property, and not the return value of the closure.
注意闭包结尾的花括号后面接了一对空的小括号。这用来告诉 Swift 立即执行此闭包。如果你忽略了这对括号,相当于将闭包本身作为值赋值给了属性,而不是将闭包的返回值赋值给属性。
Note · 注意
If you use a closure to initialize a property,
remember that the rest of the instance hasn't yet been initialized
at the point that the closure is executed.
This means that you can't access any other property values from within your closure,
even if those properties have default values.
You also can't use the implicit self property,
or call any of the instance's methods.
如果你使用闭包来初始化属性,请记住在闭包执行时,实例的其它部分都还没有初始化。这意味着你不能在闭包里访问其它属性,即使这些属性有默认值。同样,你也不能使用隐式的 self 属性,或者调用任何实例方法。
The example below defines a structure called Chessboard,
which models a board for the game of chess.
Chess is played on an 8 x 8 board,
with alternating black and white squares.
下面的示例中定义了一个 Chessboard 结构体,它构建了西洋跳棋游戏的棋盘。西洋跳棋游戏在一副黑白格交替的 8 x 8 的棋盘中进行的:

To represent this game board,
the Chessboard structure has a single property called boardColors,
which is an array of 64 Bool values.
A value of true in the array represents a black square
and a value of false represents a white square.
The first item in the array represents the top left square on the board
and the last item in the array represents the bottom right square on the board.
为了呈现这副游戏棋盘, Chessboard 结构体定义了一个属性 boardColors ,它是一个包含64个 Bool 值的数组。数组中值为 true 表示为一个黑格,值为 false 表示为一个白格。数组中第一个元素代表棋盘上左上角的格子,最后一个元素代表棋盘上右下角的格子。 .
The boardColors array is initialized with a closure to set up its color values:
boardColors 数组是同一个闭包初始化并设置颜色值的: array is initialized with a closure to set up its color values:
struct Chessboard {
let boardColors: [Bool] = {
var temporaryBoard: [Bool] = []
var isBlack = false
for i in 1...8 {
for j in 1...8 {
temporaryBoard.append(isBlack)
isBlack = !isBlack
}
isBlack = !isBlack
}
return temporaryBoard
}()
func squareIsBlackAt(row: Int, column: Int) -> Bool {
return boardColors[(row * 8) + column]
}
}Whenever a new Chessboard instance is created, the closure is executed,
and the default value of boardColors is calculated and returned.
The closure in the example above calculates and sets
the appropriate color for each square on the board
in a temporary array called temporaryBoard,
and returns this temporary array as the closure's return value
once its setup is complete.
The returned array value is stored in boardColors
and can be queried with the squareIsBlackAt(row:column:) utility function:
每当一个新的 Chessboard 实例被创建时,闭包就会被执行, boardColors 的默认值会被计算出来并返回。上面的示例中的闭包会计算出棋盘中每个格子对应的颜色,并将这些值保存到一个临时数组 temporaryBoard 中,最后在构建完成时将此数组作为闭包返回值返回。这个返回的数组会保存到 boardColors 中,并可以通过 squareIsBlackAt(row:column:) 工具函数来查询:
let board = Chessboard()
print(board.squareIsBlackAt(row: 0, column: 1))
// Prints "true".
print(board.squareIsBlackAt(row: 7, column: 7))
// Prints "false".






