properties

Properties in Swift

You are using properties all the time in Swift development. In this post you will learn all the basics.

Hint: This post has been updated to Swift 3

There are two types of properties: stored properties and computed properties. Stored properties store values (constant or variable) as part of an instance, whereas computed properties don’t have a stored value.

Stored properties

Imagine you have a class named circle:

Circle has an instance variable called  radius  with a default value of 0. In Swift, every instance variable is automatically a property. So now you have the possibility to add so called property observers. In Swift there a two types of property observers: One is called before the new value is assigned and the other one afterwards.

The property observer which is called after the assignment is marked with the keyword  didSet. In our example you can use it to check whether the assigned value is correct or not:

In the property observer you can access the old value of the property through the variable  oldValue .

You can also use the property observer  willSet which is called before the new value is assigned:

In  willSet  you have access to the new value of the property through the variable  newValue.

Computed Properties

Contrary to stored properties, computed properties don’t have a stored value. So each time you call a computed property, the value needs to be calculated. In the class  Circle  you can define the property  area  as a computed property:

A computed property always needs a getter. If it lacks a setter, the property is called a read only property. In our example, there is a good application for a setter:

Now, after assigning a new value to area ,  radius  will be calculated.

Lazy Properties

If a stored property with a default value is marked with the keyword  lazy, its default value will be initialized, when the property is called for the first time.

You should use this feature, if the initialization is expensive in terms of memory or CPU usage.

References

Title Image: @ Fabrik Bilder / shutterstock.com

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.

Amazon