Swift Properties

  Total Views : 136
  Comments : 0
  Keywords : Swift properties are the part of class or structure, Swift properties can be variables or constants in classes, structures or enumerations, Swift properties can be modified using get and set

Here we will learn properties in swift and how to use swift properties in classes, structures or enumerations, stored and lazy stored properties, computed properties, read only properties, property observers and type properties in swift with examples.

Swift Properties

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

 

In swift properties are used to store the values for a classesstructures or enumerations and properties have a 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 class with properties in 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 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 above program in swift playground we will get result like as shown below

 

Name: Suresh Dasari

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

 

We have 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 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 a stored properties during its initialization with example.

 

Following is the example of defining stored properties as a part of class or structure in 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 above program in swift playground we will get 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 same throughout the application.

 

In case if we try to modify constant property value during its initialization or with the instance of 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 above example in swift playground we will get error like as shown below

 

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

Once we assign a value to constant property that should be 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 application. Suppose we have a 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 result like as shown below

 

Welcome to Tutlane, Suresh! 

This is how we can use lazy stored properties in 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 initialization completes that’s the reason always we need to define lazy properties as a 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 a 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 result like as shown below

 

62.800000000000004

This is how we can use computed properties in 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 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 a 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 following two observers.

 

  • willSet – This observer is called just before the value is stored.
  • didSet – This is 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 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 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 super class 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 the 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 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 above example we created type property and setting value directly by using 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. 

 

PREVIOUS

Swift Structures
 

NEXT

Swift Methods  
 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User