Latest Post

How to get the Flutter Device name flutter interview questions and answers SwiftUI CollectionView

In Swift, Computed Property are a subset of a larger family of property types. The most popular properties are those that save and return a stored value; Computed properties work a little differently.

When learning to programme in Swift, all developers quickly encounter the idea of properties. One of the terms that is most frequently read, written, or discussed in programming articles, books, courses, or debates. Simply put, properties are variables and constants that we declare in Swift classes, structures, and enumerations and use to hold values. However, properties are found in all Object-Oriented Programming (OOP) languages, not just Swift.

Nevertheless, the concepts “stored” and “computed” will soon enter the conversation around properties. Even while both express their significance in some way, it is only after exploring them that one learns what they genuinely are.

What is Stored Properties

Variables or constants that hold values for instances of classes or structures are referred to as stored properties. Although it might seem apparent, variable values can always be changed. On the other hand, constants’ initial values cannot be changed after the fact.

Depending on the requirements of the application we develop, we could declare properties with default values as well. Initial values should be supplied during the initialization of the instance of the type to which a property belongs if it has merely its data type, no default value, and is not stated as optional. Keep in mind that the initial or default value for stored properties that are constants determines what the property will hold for the duration of the instance; constants are immutable and don’t change.

Class Employee { 
  var employeeName: String
  Let employeeID: Int = 12
  var department: String?
}

Three stored attributes are declared in the above Employee class. Since the employeeName parameter is of type String and lacks a default value, we will need to supply one when we create an instance of the class.

The EmployeeID is the interger and its a let constant therefore the value in the employeeID cannot be changed . It stored Property does not change the value of the EmployeeID parameter

The department parameter is used as optional in the class Employee it is supposed to store the property as optional in the Employee Class

Lazy Stored Property

One example of when to use lazy initialization is when the initial value for a property is not known until after the object is initialized or when the computation of the property is computationally expensive.

When a variable is created for the first time in Swift 4, it won’t compute the initial values thanks to a flexible attribute called a “Lazy Stored Property.” Before the variable declaration, the “lazy” modifier is used to make the variable a lazily stored property.

Use of Lazy stored Properties

  • to put off creating an entity.
  • when a property is reliant on unknowable other class components
class employee {
   lazy var eno = employeeNo()    // `var` declaration is required.
}

class employeeNo {
   var name = "Swifty"
}

var employeData = employee()
print(employeeData.employee.name)

OUTPUT

Swifty

What is a Computed Property?

A Computed property computes its property upon request—the name says it all. Adding a new property value depending on additional circumstances might be a useful addition to any of your types. This article describes their usage, when to utilise them, and the distinctions between a Computed value and a method.

Swift provides us with two different types of properties: computed properties run some code to calculate the value, and stored properties keep a value for later usage.

Here is a Student struct for comparison that has four stored properties and one Computed property. Based on merging the four stored attributes into a phrase, the Computed property produces a string.

struct Student {
    var name = "Swifty"
    var batchcolor = "blue"
    var class = "second"

    var greeting: String {
        return "Hello, my name is \(name),and I am from class \(class), and my batch color is /(batchcolor)."
    }
}

In order to access other properties and values indirectly, computed properties include a getter and an optional setter. It has several applications.

Computed properties

Before diving in, it’s helpful to be aware of a few crucial facts.

  • Consider them as bits of code that will perform a calculation each time you call them.
  • Invariably, computed characteristics are variables (never constants)
  • Classes, structs, and enums can all utilise these types of attributes.

Computed Property for Getters and Setters


All right, we’ve now shown that a Computed property produces a value. They vary from stored properties and functions in that they run some code when you call them. As of now, so nice!

Additionally, computed properties may have a unique getter and setter.

  • Each time the property is read or retrieved, a getter is run.
  • When the property is set or modified, a setter is run.
class Addition {
  var a: Int = 0
  var b: Int = 0

  // create computed property
  var add: Int {

    // retrieve value
    get {
      a + b
    }
  
    // set new value to a and b
    set(increase) {
      a = (increase + 5)
      b = (increase + 50)
    }
  }
}

var value = Addition()
value.a = 30
value.b = 40

// get value
print("Get value:", value.add)

// provide value to modify
value.add = 20

print("New a value Set:", value.a)
print("New b value Set:", value.b)

OUTPUT

Get value:70
New a value Set: 25
New a value Set: 70

We’ve generated a computed property with the name total in the aforementioned example. Within the total, we have

  1. Getter – to calculate the sum of a and b
 get {
      a + b
    }

Using “get”  in computed Properties

  • The computed property is viewable when the get keyword is used.
  • You may read data from the computed property using a getter.
  • You insert the code that will run once the computed property is invoked inside the brackets.
  • When a property is accessed, the getter is used.

2.Setter – Change the values of a and num2b

 // set new value to a and b
    set(increase) {
      a = (increase + 5)
      b = (increase + 50)
    }

Using set computed property

  • The Computed property can be modified using the set keyword. Without it, the following error occurs: It is a get-only property; you cannot set to value [your Computed property’s name].
  • You call the setter when you assign a value to the Computed property.
  • Within the setter’s braces, the value is available.
  • The compiler will automatically allot the name newValue if you do not specify a name for the given value in the setter declaration.
  • You can alter the value of other properties within the same scope by using the set method, therefore you must be aware of any dependencies connected to the Computed property.

Here, a and b can have new values assigned to them using the setter’s new value called alter.

Read only computed properties

It is required to implement the getter for a calculated property. Although it relies on the calculated property we are defining, doing so for the setter is wholly optional.

Consider a structure for storing Addition values if you want to see an illustration of that. In order to do that, we have an array and a calculated property to determine the value of the average temperature:

struct Addition {
    var add = [Double]()
    var average: Double? {
        get {
            return add.count != 0 ?
                add.reduce(0, { $0 + $1 }) / Double(add.count) :
                nil
        }
    }
}

You’ll see that there isn’t a setter present here, and it wouldn’t make sense if there were. The computed property is referred to be read-only in situations like the one described above when there is no setter.

By eliminating a few items, we can streamline the way we write read-only computed properties. Since there is no setter, it is no longer essential to explicitly specify the get body, which is the first one:

 
var average: Double? {
    return add.count != 0 ?
        add.reduce(0, { $0 + $1 }) / Double(add.count) :
        nil
}
 

By deleting the return keyword, the read-only computed property will become “lighter” as a second step. It’s not necessary to keep it in single statements:

var average: Double? {
    add.count != 0 ?
        add.reduce(0, { $0 + $1 }) / Double(add.count) :
        nil
}

The implementation of the explicit getter and the return keyword has been removed, making the computed property simpler.

Leave a Reply

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