Start a Project

Properties In Swift

Properties associate values with a particular class, structure, or enumeration.

Swift Properties are broadly classified into two types.

  1. Stored Properties: store constants and variables and are provided by classes and structures. Stored properties can be either variable stored properties (introduced by the var keyword) or constant stored properties (introduced by the let keyword).
  2. Computed Properties: Instead of storing values, these calculated values. Are provided by class structs as well as enumerations.

Note: A computed property can’t be a constant.

Example Of Swift Stored Property

Both the name and id are stored properties (constant and variable respectively) in the above snippet.

Swift Lazy Properties

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

NOTE: You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.

 

Example Of Swift Lazy Property

The property will not initalized until it gets accessed. In this example this is not very obivious though. But since the initialization can also happen inside a block, we can make it a little bit more obvious:

Swift Computed Properties

In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

In the above code getters and setters are used as get { } and set(param_name){ } on the computed property area. The getters and setters are accessed using the dot syntax. If a param name isn’t specified inside the setter, Swift assigns the default name as newValue.

Computed Properties can’t be assigned as a lazy var property. Computed Properties that have a get and set defined can’t be set as a constant let.

 

Swift Property Observers

Swift Property Observers respond to changes in the property value. These are typically used when two property values are dependent on each other. They contain two methods:

  1. willSet : This gets triggered just before the value is stored. It allows us to read the old value before its changed. We can access the new value using the keyword newValue
  2. didSet : This gets triggered after the value is stored. It lets us read both the old and new values. We can access the old value using the keyword oldValue

Property Observers get triggered every time the value is set.

Conclusion

So pls follow the above step and And if you have any issue or suggestion you can leave your message in the comment section I will try to solve this.

Exit mobile version