Properties in iOS Swift Part – 1

Updated 28 December 2020

Save

Properties are for class, structure, or enumeration to associate values. Properties in swift are basically of two types:-

  1. Stored Properties
  2. Computed Properties

1 Stored Properties

Let first see Stored Properties, its main role is to store constant and variable as a part of the instance. It is only provided by classes and structure. At the time of initialization, you can set and modify the initial values.

Let see an example of it using structure.

In the above example, the width is constant stored property and height is variable stored property.

Let see one more example

In this above example newBox.Height gives an error. Because we have created an instance and assigned it to a constant(let newBox).

This is because the structure is of the value type. This will not give an error in the case of class because the class is a reference type.

Lazy Stored Properties

It is a stored property whose default value is not initialized until it is used for the first time. it is indicated by the “lazy” keyword. Also, it must be declared as a variable, because constant properties have value before the initialization completes.

Let see an example of it.

In this above example “someFile” is declared as lazy. So it is not yet initialized unless it is called, Although the Testclass is initialized.

2 Computed Properties

Computed properties provide the getter and optional setter. Also, it does not store the value. It is defined by Class, Struct, and enum.

Let see an example.

Shorthand Setter Declaration

If the name of the setter is not defined for the new value, then the default “newValue” is used.

Let see one example

Read-Only Computed Properties

In this, there is only a getter and not a setter

Example

Property Observers

It responds to property value changes. It is called every time when the property value set.

You can set either one or both observers to the property.

Observers

i) wiilSet => it is called when the value is just to store.

ii) didSet => It is called immediately when the value is stored.

Let see an example.

 

Conclusion

 

Thanks for reading this blog. I hope you will get the basic idea of property.

You can also check other blogs from here. if you have any issue or suggestion you can leave your query/suggestion in the comment section.

Reference

Swift Doc

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home