Various Property in Swift

Variables used as a whole, such as classes, structures, and enums, are called properties. Property types include stored property, computed property, and type property. Let's go through them one by one in order.

Stored property

Stored property is the most common property and are used to store values. You can set the initial value, and the class stores the value associated with the instance.

let name = "Hohyeon Moon"
var age = 25

Lazy Stored property

Lazy stored property have a characteristic that their initial value is not calculated until the property is used for the first time. You can use the lazy keyword before the declaration, and let cannot be used as a lazy stored property.

class Position {
  lazy var point: CoordinatePoint = CoordinatePoint()

Computed property

Computed property is a property that does not actually store a value, but indirectly sets or receives a value with the get and set keywords.

var wallet: Int = 10000

var counter: Int {
    get {
        return wallet
    set(money) {
        wallet += money

Type property

As a type property, you can define a property according to the type, not the property of the instance. You can set type property on a value type using the static keyword, and you can set type properties on a class type using the class keyword. When you get a value, you can get it through the name of the class.

struct AudioChannel {
    static let level = 10
    static var maxLevel = 0


Property observer

Property Observers execute the specified code when the value of the property is changed. It cannot be used for lazy properties, and can only be used with stored properties. willSet is called just before the property value is changed, and didSet is called right after the property value is changed. newValue is passed automatically in willSet and oldValue in didSet.

class Account {
    var credit: Int = 0 {
        willSet {
            print("Credit is changing from \(credit) to \(newValue) won.")
        didSet {
            print("Credit is changing from \(oldValue) to \(credit) won.")

let myAccount = Account() = 1000