Properties | Swift | iOS | Stored

Properties associate value with a paticular class, structure or enumeration. Stored Properties (provided by class, struct and enum) store constant and variable values as part of instance, whereas Computed Properties (provided by class and struct only) calculate a value. Properties can also be associated with type itself its called Type Properties. Apart from that we can add observers to monitor the changes in a property’s value there you can response to your custom actions, we can add it to Stored Properties and also property that a subclass.

Stored Properties

Simplest form, its a constant or variable that is stored as a part of an instance of a particuler class, struct or enum.

struct Box  {
    var height  : Int
    let width   : Int
}

var box1 = Box(height: 101, width: 10)

It can be either Variable stored property (introduced by var) or Constant stored property(introduced by let). if its Variable stored property than we can set initial value during initialization and if Constant stored property without default value than yes as well.

Lazy Stored Properties

Whose initial values is not calculated until the first time it is used. they are useful when the initial value for a property is dependent on other factors or sometime if the initial value for a property requires complex or computationally expensive setup that should not be performed unless it is needed.

class DataImporter  {
    /*
     This class is responsible for fetching and holding the file data.
    */
    var fileName = "data.json"
}

class DataManager   {
    var data = [String]()
    lazy var importer = DataImporter()
}

let dManager = DataManager()
dManager.data.append("One")
dManager.data.append("two")

Now here the interseting part is till now importer property is not created. because is marked as lazy so the property is only created when the importer property is first accessed.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s