In Swift world, there are many data types such as classstruct and enumeration, etc. What are their differences? class is in reference type but struct is in value type.

Each property can be categorised as stored property and computed property. The first one has a fixed value but the later one’s value is calculated every time it is accessed. Moreover, Swift provides observers to stored property to listen to the value changes callback — **willSet** and **didSet**.

The above terminologies are all the common challenges for beginners. In this article, I would briefly introduce them and point out some of the tips. Hope you find this useful.

Reference type (class) Vs Value type (struct)

Image for post

Class and Struct are the two main memory type in Swift. Class is in reference type which points to the memory address of a memory but struct is in value type which points to the data stored at the memory address.

Therefore, a constant class instance has a constant memory address and its variable data can be changed at anytime. However, a constant struct instance has constant data but variable address. Refer to line 15, It will throw a compile error when the data of a constant struct is changed.

Struct is recommended to be the first choice. However, developer should choose class when code is designed to be subclassed and has to be accessed by Objective-C codes.

Computed property — Getter & Setter

Computed property is a special property which has a getter function together with a setter function. Its value is determined by getter function every time it is accessed (See line 15) instead of a stored property with fixed value. Setter function is called when the value is altered (See line 19).

The common use case would be the data handling with persistent storage. The getter function can retrieve the data from storage and setter function can set the data to storage directly. It can simplify the code very much.

#ios-app-development #swift-programming #property #ios #101

Swift 101 — Basic Property
1.20 GEEK