Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Initialization

Swift Initialization

Initialization is the process of setting initial values for every stored property and completing the necessary preparation when creating an instance of a class, struct, or enum.

This process is carried out by an initializer, declared with the keyword init. An initializer returns no value; its job is to ensure the instance is in a valid state before its first use.


Initial Assignment of Stored Properties

When an instance is created, all stored properties must have initial values, which can be given in two ways: a default value at the point of declaration, or an assignment in an initializer.

Assigning a property's value in an initializer is a direct setting and does not trigger property observers.

Example

import Foundation

class

Rectangle

{

    var length

=

6.0

   

// Give a default value directly at the point of declaration

    var breadth

:

Double  

// No default value, must be assigned in the initializer

    init

(

breadth

:

Double

)

{

        self.

breadth

=

breadth

   

}

}

let rect

=

Rectangle

(

breadth

:

12.0

)

print

(

"Area: (rect.length * rect.breadth)"

)

Running result:



面积:72.0

If a property has a default value, its type annotation can be omitted, and Swift infers the type from the default value, for example length above is inferred as Double.


Initializers, Default Initializers, and Memberwise Initializers

The simplest form of an initializer is an init() with no parameters, used to set fixed initial values for properties.

If all of a type's stored properties have default values and it does not write any initializer of its own, Swift automatically provides two kinds of initializers.

Constructor Applicable to types Requirements for generation Call form
Default initializer Class, struct All stored properties have default values and there is no custom initializer TypeName()
Memberwise initializer Structure All stored properties have default values and there is no custom initializer TypeName(a: 1, b: 2)

Example

import Foundation

// All stored properties have default values, so the class automatically gets the default initializer init()

class

ShoppingListItem

{

    var name

:

String

?

    var quantity

=

1

    var purchased

=

false

}

let item

=

ShoppingListItem

(

)

print

(

"Name: (item.name ?? "

None

"), quantity: (item.quantity), purchased: (item.purchased)"

)

// When a struct has no custom initializer, it automatically gets a memberwise initializer

struct

Size

{

    var width

=

0.0

    var height

=

0.0

}

let size

=

Size

(

width

:

3.0

, height

:

4.0

)

print

(

"Width: (size.width), height: (size.height)"

)

Running result:



名字:无,数量:1,已购买:false

宽:3.0,高:4.0

Once you write any custom initializer for a struct, the memberwise initializer is no longer generated automatically.


Initialization Parameters and External Parameter Names

An initializer can take parameters to pass different initial values when creating an instance.

Unlike normal functions, an initializer's parameters are both local and external names by default, so every parameter must have a label at the call site; an underscore _ can explicitly omit a parameter's external name.

Example

import Foundation

struct

Color

{

    let red, green, blue

:

Double

   

// An initializer's parameters serve as both local and external names by default

    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

   

}

   

// Use _ to omit the external name

    init

(

_ gray

:

Double

)

{

        red

=

gray

        green

=

gray

        blue

=

gray

   

}

}

let magenta

=

Color

(

red

:

1.0

, green

:

0.0

, blue

:

1.0

)

let halfGray

=

Color

(

white

:

0.5

)

let gray

=

Color

(

0.25

)

print

(

magenta.

red

, halfGray.

green

, gray.

blue

)

Running result:



1.0 0.5 0.25

Note:An initializer's parameters have external labels by default, consistent with methods (SE-0046 unified the rules starting in Swift 3). Labels are actually clearer:Color(red:green:blue:) The difference between Color(white:) you can tell them apart at a glance.


Optional Property Types

If a stored property is logically allowed to be empty, declare it as an optional type.

An optional property is automatically initialized to nil, so there is no need to assign it manually in an initializer.

Example

import Foundation

class

SurveyQuestion

{

    let text

:

String          

// A constant property can be assigned only once during initialization

    var response

:

String

?

   

// An optional property is automatically initialized to nil

    init

(

text

:

String

)

{

        self.

text

=

text

   

}

    func ask

(

)

{

        print

(

text

)

   

}

}

let question

=

SurveyQuestion

(

text

:

"Which feature of Swift do you like most?"

)

question.

ask

(

)

print

(

"Answer: (question.response ?? "

Not answered yet

")"

)

Running result:



你最喜欢 Swift 的哪个特性?

回答:尚未回答

If an optional property's value can be determined at initialization, you can assign it as usual; if not, simply leave it empty.


Modifying Constant Properties During Initialization

A constant property declared with let is not completely unassignable; as long as its value is determined before the end of initialization, you can assign it once in the initializer.

For classes, a constant property can only be modified in the initializer of the class that defines it, not in a subclass.

Example

import Foundation

class

Rectangle

{

    let width

:

Double

    let height

:

Double

    let area

:

Double          

// A constant, but it can be computed and then assigned before initialization ends

    init

(

width

:

Double, height

:

Double

)

{

        self.

width

=

width

        self.

height

=

height

        self.

area

=

width

height

   

}

}

let rect

=

Rectangle

(

width

:

6.0

, height

:

12.0

)

print

(

"Area: (rect.area)"

)

Running result:



面积:72.0

area is computed from width and height; assigning it at the end of the initializer both satisfies the rules for let and ensures it is correct once the instance is fully created.


Two-Phase Initialization and Safety Checks

Swift's class initialization is divided into two phases, designed to prevent properties from being accessed before they are fully initialized.

Swift two-phase initialization flowchart: Phase 1 goes bottom-up, a subclass first initializes its own stored properties and then calls up to super.init until the root class; Phase 2 goes top-down, starting from the root class and customizing the instance level by level; the right side marks three safety checks

Phase 1 works from the bottom up: the subclass first initializes its own stored properties, then calls the parent class initializer upward, completing property initialization layer by layer along the entire inheritance chain.

Phase 2 works from the top down: starting from the topmost parent class, each layer has a chance to further customize properties once the new instance is ready.

Example

import Foundation

class

Animal

{

    var name

:

String

    var description

:

String

{

       

return

"Animal: (name)"

   

}

    init

(

name

:

String

)

{

        print

(

"Phase 1: Animal.init begins"

)

        self.

name

=

name

        print

(

"Phase 1: Animal.init ends"

)

   

}

}

class

Dog

:

Animal

{

    var breed

:

String

    init

(

name

:

String, breed

:

String

)

{

        print

(

"Phase 1: Dog.init begins"

)

        self.

breed

=

breed

        super.

init

(

name

:

name

)

         

// Call the parent class initializer to complete phase 1

        print

(

"Phase 2: Dog.init can access self.description -> (self.description)"

)

        self.

name

=

name

"(registered)"

 

// Only in phase 2 can the parent class's properties be modified

        print

(

"Phase 2: Dog.init ends"

)

   

}

}

let dog

=

Dog

(

name

:

"Wangcai"

, breed

:

"Shiba Inu"

)

print

(

dog.

description

)

Running result:



阶段一:Dog.init 开始

阶段一:Animal.init 开始

阶段一:Animal.init 结束

阶段二:Dog.init 可以访问 self.description -> 动物:旺财

阶段二:Dog.init 结束

动物:旺财(已登记)

From the output order, you can see that the parent class initializer must finish before the subclass can enter phase 2 and modify inherited properties.

The Swift compiler constrains this process with four safety checks:

Number Security check
1 A designated initializer must ensure that all stored properties introduced by its class are fully initialized before it can delegate up to the parent class initializer.
2 A designated initializer must call the parent class initializer before it can set new values for inherited properties.
3 A convenience initializer must call another initializer in the same class before it can assign new values to any property.
4 Before phase 1 is complete, an initializer cannot call instance methods, cannot read property values, and cannot reference self.

Initializer Delegation for Value Types

An initializer can call other initializers to share part of the initialization work; this process is called initializer delegation and can reduce duplicated code.

Structs and enums are value types and do not support inheritance, so they can only delegate to other initializers they provide themselves, called with self.init.

Example

import Foundation

struct

Size

{

    var width

=

0.0

, height

=

0.0

}

struct

Point

{

    var x

=

0.0

, y

=

0.0

}

struct

Rect

{

    var origin

=

Point

(

)

    var size

=

Size

(

)

    init

(

)

{

}

    init

(

origin

:

Point, size

:

Size

)

{

        self.

origin

=

origin

        self.

size

=

size

   

}

   

// Initializer delegation for value types: use self.init to call other initializers of the same type

    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

)

   

}

}

let basic

=

Rect

(

)

let centered

=

Rect

(

center

:

Point

(

x

:

4.0

, y

:

4.0

)

, size

:

Size

(

width

:

3.0

, height

:

3.0

)

)

print

(

"basic origin: (basic.origin.x), (basic.origin.y)"

)

print

(

"centered origin: (centered.origin.x), (centered.origin.y)"

)

Running result:



basic 原点:0.0, 0.0

centered 原点:2.5, 2.5


Initializer Delegation for Classes: Designated and Convenience Initializers

Because classes have inheritance relationships, initializers are divided into two roles with different responsibilities.

Type Responsibility Declaration Method Calling rules
Designated initializer Initialize all properties introduced by this class and call the parent class's designated initializer upward init(...) Every class must have at least one
convenience initializer providing a more convenient call entry point for a designated initializer convenience init(...) It must use self.init to call other initializers in the same class

In the following example, Recipe inherits its superclass's convenience initializers by overriding all of the superclass's designated initializers.

Example

import Foundation

class

Food

{

    var name

:

String

   

// Designated initializer: responsible for initializing all stored properties of the class

    init

(

name

:

String

)

{

        self.

name

=

name

   

}

   

// Convenience initializer: must call other initializers in the same class via self.init

    convenience init

(

)

{

        self.

init

(

name

:

"Unnamed"

)

   

}

}

class

Recipe

:

Food

{

    var quantity

:

Int

   

// Designated initializer: initialize its own properties first, then call the superclass's designated initializer

    init

(

name

:

String, quantity

:

Int

)

{

        self.

quantity

=

quantity

        super.

init

(

name

:

name

)

   

}

   

// Override the superclass's designated initializer, a prerequisite for inheriting its convenience initializers

    override init

(

name

:

String

)

{

        self.

quantity

=

1

        super.

init

(

name

:

name

)

   

}

}

let food

=

Food

(

)

print

(

food.

name

)

let recipe

=

Recipe

(

name

:

"RUNOOB Stew"

, quantity

:

3

)

print

(

"(recipe.name): (recipe.quantity) servings"

)

// Recipe overrides all of its superclass's designated initializers, so it automatically inherits Food's convenience init()

let inherited

=

Recipe

(

)

print

(

inherited.

name

)

Running result:



[未命名]

RUNOOB 炖菜:3 份

[未命名]


Initializer Inheritance Rules

Swift subclasses do not inherit their superclass's initializers by default; they are inherited automatically only when specific conditions are met.

Rule 1: If a subclass defines no designated initializers of its own, it automatically inherits all of its superclass's designated initializers.

Rule 2: If a subclass implements all of its superclass's designated initializers (whether inherited via Rule 1 or overridden by itself), it automatically inherits all of the superclass's convenience initializers.

The Recipe above is an example of Rule 2: it overrides Food's only designated initializer, init(name:), and therefore inherits the convenience initializer init() as well.

Note:When overriding a superclass's designated initializer, even if the subclass's implementation has no extra parameters, you must write the override modifier.


Required Initializers

Adding required before an initializer means all subclasses must implement that initializer.

Subclasses must also write required when implementing it, rather than override.

Example

import Foundation

class

Base

{

    var value

:

Int

   

// required means subclasses must implement this initializer

    required init

(

value

:

Int

)

{

        self.

value

=

value

   

}

}

class

Derived

:

Base

{

   

// Subclasses must also write required when implementing it

    required init

(

value

:

Int

)

{

        super.

init

(

value

:

value

10

)

   

}

}

let d

=

Derived

(

value

:

5

)

print

(

"Derived's value: (d.value)"

)

Running result:



Derived 的值:50


Failable Initializers init? and init!

If initialization may fail because of invalid parameters or unavailable resources, you can define a failable initializer that returns nil on failure.

A failable initializer is declared with init?, and its return type is an optional type.

Example

import Foundation

struct

Animal

{

    let species

:

String

   

// Failable initializer: returns nil when the condition is not satisfied

    init

?

(

species

:

String

)

{

       

if

species.

isEmpty

{

return

nil

}

        self.

species

=

species

   

}

}

let giraffe

=

Animal

(

species

:

"Giraffe"

)

let unknown

=

Animal

(

species

:

""

)

if

let giraffe

{

    print

(

"Initialization succeeded: (giraffe.species)"

)

}

if

unknown

==

nil

{

    print

(

"Initialization failed: species is empty"

)

}

// Failable initializer for an enum: use self to directly select a member

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

       

}

   

}

}

let unit

=

TemperatureUnit

(

symbol

:

"F"

)

print

(

unit

==

.

fahrenheit

)

print

(

TemperatureUnit

(

symbol

:

"X"

)

==

nil

)

Running result:



构造成功:长颈鹿

构造失败:species 为空

true

true

There is also init!, which returns an implicitly unwrapped optional; if it fails and you use it without checking, the app crashes, so it is no longer recommended.

Example

import Foundation

class

Student

{

    let name

:

String

   

// init! returns an implicitly unwrapped optional; when nil, it crashes at the point of use, not recommended

    init

!

(

name

:

String

)

{

       

if

name.

isEmpty

{

return

nil

}

        self.

name

=

name

   

}

}

// When explicitly annotated as a non-optional type, the result of init! is implicitly unwrapped

let student

:

Student

=

Student

(

name

:

"Runoob"

)

print

(

"Student: (student.name)"

)

let empty

=

Student

(

name

:

""

)

print

(

"Is the result of the empty-name initialization nil: (empty == nil)"

)

Running result:



学生:Runoob

空名字构造结果是否为 nil:true

Class failable initializers have one more restriction: failure can only occur after all properties have been initialized and all initializer delegation calls have completed.


Common questions

Errors related to initialization mostly occur in the following scenarios.

Error: property not initialized at super.init call

Before calling super.init, you must assign values to all stored properties introduced by the subclass itself; this is the first safety check.

The memberwise initializer of the struct is gone

As soon as you write any custom initializer for a struct, the memberwise initializer is no longer synthesized automatically. If you need it, move the custom initializer into an extension to keep it.

Why can't a subclass directly use its superclass's convenience initializer?

Because the subclass has not yet implemented all of its superclass's designated initializers. Once all designated initializers are implemented according to Inheritance Rule 2, the convenience initializers are inherited automatically.

Error when modifying a let property in an initializer

A constant property can be assigned only once during initialization of the class that defines it. If you try to modify a superclass's constant property in a subclass, the compiler rejects it outright.