Swift Properties

In swift, properties are used to describe attributes of an object and those can be a constants or variables in classes, structures or enumerations.

 

In swift properties are used to store the values for classesstructures or enumerations and properties have getter and setter methods to modify or set property values based on our requirements.

Swift Define a Property

Following is the simple example of creating a class with properties in a swift programming language. 

 

class UserDetails {

var firstName: String = ""

var lastName: String = ""

}

If you observe above example we defined a class “UserDetails” with two properties (firstName, lastName).

Swift Assign and Access Properties

Following is the example of declaring and assigning values to the defined properties in the class.

 

class UserDetails {

var firstName: String = ""

var lastName: String = ""

}

var uinfo = UserDetails()

uinfo.firstName = "Suresh"

uinfo.lastName = "Dasari"

print("Name: \( uinfo.firstName) \(uinfo.lastName)")

If you observe above example we defined a two properties “firstName”, “lastName” and these values are associated with class “UserDetails”. After that we created instance for that class and accessing the properties within the class to assign values based on our requirements.

 

When we run the above program in swift playground we will get a result like as shown below

 

Name: Suresh Dasari

The same way we can define and access properties in structures and enumerations based on our requirements in swift programming language.

 

We have a different type of properties available in swift programming language those are

 

  • Stored Properties
  • Computed Properties

Swift Stored Properties

In swift stored property is a constant or variable and it’s stored as a part of an instance of a particular class or structure. The stored property can be used to store a variable with var keyword and a constant with let keyword.

 

We can provide a default values for a stored properties as a part of its definition and we can modify the initial values of a stored properties during its initialization.

 

Now we will see how to define stored properties in classes and how to modify initial values of stored properties during its initialization with example.

 

Following is the example of defining stored properties as a part of class or structure in a swift programming language.

 

struct UserDetails {

var firstName: String = "Rohini"

let lastName: String

}

var uinfo = UserDetails(firstName: "Suresh", lastName: " Dasari")

print("Name: \( uinfo.firstName) \(uinfo.lastName)")

If you observe above example we defined two stored properties (firstName, lastName) one as a variable (var) and another one as constant (let) with initial values. After that we created instance of structure and modified initial values during its initialization.

 

When we run the above program in swift playground we will get a result like as shown below

 

Name: Suresh Dasari

This is how we can define stored properties in classesstructuresenumerations based on our requirements in swift programming language.

Stored Properties for Constant Structure Instances

In swift, we can define a class or structure with stored properties as a constant. In case if we define constant property with initial value then it’s not possible for us to modify that value because once the value assigned to a constant variable that should be the same throughout the application.

 

In case if we try to modify constant property value during its initialization or with the instance of a class, the compiler will throw an error.

 

Following is the example of modifying constant stored property value after initializing value during creation of instance of class.

 

struct UserDetails {

var firstName: String = "Rohini"

let lastName: String

}

var uinfo = UserDetails(firstName: "Suresh", lastName: " Dasari")

uinfo.lastName = "Alavala"

print("Name: \( uinfo.firstName) \(uinfo.lastName)")

If you observe above example we defined a constant property “lastName” and assigning value to the variable during creation of instance of class. After that again we are trying to modify the value of constant variable.

 

When we try to run the above example in swift playground we will get an error like as shown below

 

Error: cannot assign to property: ‘lastName’ is a ‘let’ constant

Once we assign a value to the constant property that should be the same throughout the application otherwise it will throw an error. For more information on constants check this Swift Constants

Swift Lazy Stored Properties

In swift lazy stored property is a property whose initial value is not loaded until the first time the property value is used. In swift, we can define a lazy stored property by using lazy keyword before its declaration.

 

In swift lazy stored properties are useful when the initial value of property not required to load until it is used in the application. Suppose we have one property and we need to perform some complex operations to load or initialize the value but it’s required only in specific places in that case if we use lazy stored properties those values will not be load until we use it in our code.

 

Now we will see how to use lazy stored properties in swift applications with examples.

 

Following is the example of using lazy stored property in swift programming language.

 

class Student {

var name: String

lazy var studentInfo: String = {

return "Welcome to Tutlane, \(self.name)!"

}()

init(name: String) {

self.name = name

}

}

let stu = Student(name: "Suresh")

print(stu.studentInfo)

If you observe above example we defined a lazy stored property “studentInfo” using lazy keyword. This property value will not loaded until the print statement call the property from student class instance.

 

When we run above program in swift playground we will get a result like as shown below

 

Welcome to Tutlane, Suresh! 

This is how we can use lazy stored properties in a swift programming language based on our requirements.

 

Here we need to remember that always we need to declare lazy stored properties as a variable (var) because its value not retrieved until instance initialization completes but for constant (let) properties must have a value before the initialization completes that’s the reason always we need to define lazy properties as variables.

Swift Computed Properties

In swift unlike stored properties, computed properties will not store a value instead computed properties will provide a getter and an optional setter to retrieve and set other property values indirectly. We can define computed properties in classesstructures and enumerations based on our requirements.

 

Following is the example of defining computed properties using getter and setter to set values in swift programming language.

 

class Circle {

var radius : Double?

var cval : Double?

var Area: Double {

get {

return radius! * radius!

}

set (newArea){

cval = Double(newArea) * 3.14

}

}

}

let result = Circle()

result.Area = 20

print(result.cval)

If you observe above example we are setting new value for the property “Area” using getter and setter properties.

 

When we run above program in swift playground we will get a result like as shown below

 

62.800000000000004

This is how we can use computed properties in a swift programming language to use values without storing based on our requirements.

Swift Read-Only Computed Properties

A computed property with only getter but no setter is known as a read-only computed properties. In swift we can access read-only computed property through dot (.) syntax and it always return a value.

 

Following is the example of using read-only computed properties in a swift programming language.

 

class Multiplication {

var num1 : Int = 5

var num2 : Int = 5

var multiply: Int {

get {

return num1 * num2

}

}

}

let r = Multiplication()

print(r.multiply)

In above example we defined two properties with default values in class and multiplying those two numbers using getter. After that we created an instance for the class and accessing the getter value using dot (.) syntax.

 

When we run above program in swift playground we will get result like as shown below

 

25

This is how we can use read-only computed properties to set the values using getter property in swift programming language.

Swift Property Observer

In swift property observers are used to observe and respond to the changes in property value and these property observers will call every time whenever the property value changes, even if the new value of property same as property current value. 

 

In swift, the changes in properties can be observed by using the following two observers.

 

  • willSet – This observer is called just before the value is stored.
  • didSet – This is an observer is called after the new value is stored.

In swift, we can use property observers in any stored properties, except lazy stored properties.

 

Following is the example of using willSet and didSet properties in a swift programming language.

 

class Changes {

var num1: Int = 10 {

willSet(newvalue) {

print("Value of \(newvalue)")

}

didSet {

if num1 > oldValue  {

print("Added \(num1 - oldValue)")

}

}

}

}

let result = Changes()

result.num1 = 34

result.num1 = 987

If you observe above example we used willSet and didSet observers and these properties are called whenever the value of property is getting changed.

 

When we run the above program in swift playground we will get result like as shown below

 

Value of 34

Added 24

Value of 987

Added 953

Swift Type Property

In swift, instance properties are associated with an instance of class or structure, the type properties are associated with a type itself, not belongs to any instance of the type.

 

In swift, we can define a type property with static keyword and for computed type properties and for class types we need to use class keyword but it won’t allow to override the superclass methods or variables. 

 

Following is the example of using type property in swift programming language.

 

struct typepro {

static let msg = "Welcome to Tutlane"

}

 

class Class1 {

func test() { print(typepro.msg) }

}

 

class Class2 {

func test() { print(typepro.msg) }

}

var ss = Class1()

ss.test()

If you observe above example we defined a type property with static keyword and accessing type property values by referencing the name and using dot syntax to access the value.

 

When we run above program in swift programming language we will get result like as shown below.

 

Welcome to Tutlane

Swift Querying and Setting Type Properties

In swift, type properties are queried and we can then set the value with dot (.) syntax just like when we create an instance and assign values to properties. However, the type properties are queried and set properties value on the type, not on an instance of that type.

 

Following is the example of using type property in swift programming language.

 

struct typerepo {

static var msg = "Welcome"

}

print(typerepo.msg)

typerepo.msg = "Welcome to Tutlane"

print(typerepo.msg)

If you observe the above example we created type property and setting the value directly by using an instance of that type. 

 

When we run above program in swift programming language we will get result like as shown below.

 

Welcome

Welcome to Tutlane

This is how we can define and use properties in swift programming language based on our requirements.