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

Swift Properties

Swift Properties

Properties are data carried by types and instances; Swift divides them into two main categories: stored properties and computed properties.

A stored property actually occupies memory to hold a value, while a computed property is calculated on each access and uses no storage.

This article covers stored and computed properties, read-only computed properties, property observers, the lazy stored property, and the easily confused difference between the type properties static and class.


Stored and computed properties

A stored property is declared with var or let and directly holds a value.

A computed property must be declared with var and reads and writes through two blocks, get and set; it stores no data itself.

Example

struct

RunoobRect

{

    var originX

:

Double

=

0.0

   

// Stored property: actually holds a value

    var width

:

Double

=

0.0

     

// Stored property

    var centerX

:

Double

{

       

// Computed property: calculated on each access

        get

{

originX

width

/

2

}

        set

{

originX

=

newValue

width

/

2

}

   

}

}

var rect

=

RunoobRect

(

originX

:

10

, width

:

20

)

print

(

rect.

centerX

)

   

// get runs on read

rect.

centerX

=

50

     

// set runs on write, and newValue is 50

print

(

rect.

originX

)



20.0

40.0

In the set block you can use the default name newValue directly, or specify your own parameter name by writing set(newCenter) { ... }.

Note:A computed property cannot be written as let. let means the value never changes once set, whereas a computed property has no value of its own, only a result produced on each access.


Read-only computed properties

A computed property that provides only get and no set is a read-only computed property; in this case the get keyword can be omitted.

Example

struct

RunoobSquare

{

    var side

:

Double

   

// Only get, so the get keyword can be omitted

    var area

:

Double

{

side

side

}

   

// Writing get explicitly is completely equivalent

    var perimeter

:

Double

{

        get

{

side

4

}

   

}

}

let square

=

RunoobSquare

(

side

:

3

)

print

(

square.

area

, square.

perimeter

)



9.0 12.0

A read-only computed property can be read with dot syntax like a normal property, but attempting to assign to it is a compile-time error.

A struct instance declared with let can also read a read-only computed property, because it only reads and never writes.


Property observers willSet and didSet

Property observers watch for changes to a stored property; willSet is called before the assignment and didSet after it.

Swift property classification tree: properties are divided into stored properties and computed properties; stored properties include ordinary storage, lazy deferred storage, and property observers; computed properties include read-only and read-write; the right side marks type properties static and class, the bottom notes that computed properties cannot have observers and that observers are not triggered during initialization

The most easily overlooked point is that assigning a value to a property during initialization does not trigger the observers.

Example

class

RunoobCounter

{

    var total

:

Int

{

        willSet

{

print

(

"willSet: (total) -> (newValue)"

)

}

        didSet  

{

print

(

"didSet: (oldValue) -> (total)"

)

}

   

}

    init

(

total

:

Int

)

{

        self.

total

=

total  

// Observers are not triggered during initialization

   

}

}

let counter

=

RunoobCounter

(

total

:

5

)

print

(

"Initialization complete, total = (counter.total)"

)

counter.

total

=

10

     

// This is a real assignment, so the observers are triggered



初始化完成,total = 5

willSet: 5 -> 10

didSet: 5 -> 10

You can also specify your own parameter names for the observers; if you omit them, the defaults newValue and oldValue are used.

Example

class

RunoobScore

{

    var value

:

Int

=

0

{

        willSet

(

newValue

)

{

print

(

"About to write (newValue)"

)

}

        didSet

(

oldValue

)

 

{

print

(

"Old value (oldValue)"

)

}

   

}

}

let score

=

RunoobScore

(

)

score.

value

=

90



即将写入 90

旧值 0

Property observers can only be added to stored properties; when overriding an inherited property in a subclass, you can add observers to it as well, as described in "Swift Inheritance》。

Note:Assigning an initial value to a property in init does not trigger willSet and didSet; only assignments after initialization is complete do. If you need to run some logic during initialization, write it directly in init.


The lazy stored property

A stored property marked with lazy computes its initial value only on first access, then reuses that result afterward.

It suits cases where initialization is expensive or depends on other properties.

Example

class

RunoobLoader

{

    lazy var content

:

String

=

{

        print

(

"Starting to load data..."

)

       

return

"Data from www.runoob.com"

   

}

(

)

}

let loader

=

RunoobLoader

(

)

print

(

"Instance created"

)

print

(

loader.

content

)

 

// First access, the closure runs

print

(

loader.

content

)

 

// Second access, the cached result is returned directly



实例已创建

开始加载数据……

www.runoob.com 的数据

www.runoob.com 的数据

A lazy property must be declared with var, because its value is written only on first access, whereas a let property cannot be assigned after initialization.

Note:A lazy property is not thread-safe. If multiple threads access the same lazy property for the first time at once, the closure may run more than once; in concurrent situations you must add your own lock or use another approach.


Type properties: the difference between static and class

A type property belongs to the type itself rather than to any instance, and is accessed through the type name.

A stored type property must use static; class can only modify overridable computed type properties, not stored properties.

Example

struct

RunoobConfig

{

   

static

var siteName

=

"RUNOOB"

 

// Stored type property: must use static

   

static

let version

=

"1.0"

     

// Constant type properties also use static

}

print

(

RunoobConfig.

siteName

, RunoobConfig.

version

)

class

RunoobBase

{

   

static

var stored

=

"Stored type, cannot be overridden by subclasses"

   

static

var staticComputed

:

String

{

"Static computed type"

}

   

// class can only modify overridable computed type properties

   

class

var overridable

:

String

{

"The superclass's computed type property"

}

}

class

RunoobSub

:

RunoobBase

{

    override

class

var overridable

:

String

{

"The subclass's overridden computed type property"

}

}

print

(

RunoobBase.

overridable

)

print

(

RunoobSub.

overridable

)

print

(

RunoobSub.

stored

)

 

// Stored type properties can be inherited and accessed by subclasses



RUNOOB 1.0

父类的计算型类型属性

子类重写后的计算型类型属性

存储型,子类不可重写

The keyword Can it modify stored properties Can it be overridden by subclasses Applicable locations
static Yes No Structs, enums, and classes all can
class No Yes Only usable on a class's computed properties, methods, and subscripts

A common pattern is to declare shared constants as static let and behavior that subclasses need to customize as class var or class func.

Note:Do not write class var name = "..."; using class for a stored type property is a direct compile-time error and must be changed to static.


Global and local variables

A variable declared outside a type at file scope is a global variable, while one declared inside a function is a local variable.

Global variables and type properties are lazily initialized by default, created only on first access, just like lazy; local variables are initialized when execution reaches their declaration.

Example

// Global variable, initialized only on first access

var runoobGlobal

=

"www.runoob.com"

func showLocal

(

)

{

    var local

=

"Local variable"

    local

=

", visible only inside the function"

 

// Local variables can be modified

    print

(

local

)

}

showLocal

(

)

print

(

runoobGlobal

)



局部变量,只在函数内可见

www.runoob.com

Global variables can likewise have property observers, written the same way as for ordinary stored properties.

Example

var runoobCount

=

0

{

    didSet

{

print

(

"Global variable changed to (runoobCount)"

)

}

}

runoobCount

=

5



全局变量被修改为 5


Common questions

Below are a few frequently asked questions about properties.

Can a computed property have property observers?

No. Observers can only be added to stored properties, because a computed property executes code on every access, so wrapping it in another observer would be meaningless.

If you need extra processing in a computed property, just put the logic directly in get and set.

What is the difference between lazy and a computed property?

lazy is a genuine stored property: once the value is computed it is saved, so the second access does not recompute it.

A computed property re-runs get on every access and does not cache the result; choose between them based on whether the result needs to be reused.

How to choose between static and class

First consider whether you are writing a stored or a computed property: a stored property can only use static.

If it is a computed property, then consider whether subclasses need to override it: use class if overriding is needed, otherwise use static.

Why don't property observers fire in init?

The job of the initialization phase is to establish initial values for properties; at that point a property has no "old value" yet, so observers naturally do not apply.

The official documentation states this explicitly, so logic that relies on didSet for validation or synchronization must account for the initialization path.