Swift Properties (Stored, Computed) Example

1. Introduction

In Swift, properties associate values with a particular class, structure, or enumeration. Properties are further categorized into two types: Stored Properties and Computed Properties. Stored properties store constant and variable values as part of instances, while computed properties calculate a value.

2. Source Code Example

// Define a structure for a rectangle
struct Rectangle {
    // Stored properties
    var length: Double
    var breadth: Double

    // Computed property to calculate area of the rectangle
    var area: Double {
        return length * breadth
    }

    // Computed property with getter and setter for perimeter
    var perimeter: Double {
        get {
            return 2 * (length + breadth)
        }
        set(newPerimeter) {
            length = newPerimeter / 4
            breadth = newPerimeter / 4
        }
    }
}

// Create an instance of the Rectangle structure
var myRectangle = Rectangle(length: 10.0, breadth: 5.0)
print("Area of the rectangle is \(myRectangle.area)")  // Using the computed property 'area'
print("Perimeter of the rectangle is \(myRectangle.perimeter)") // Using the getter of the computed property 'perimeter'

// Setting a new perimeter using the setter of the computed property 'perimeter'
myRectangle.perimeter = 30.0
print("New length of the rectangle is \(myRectangle.length)")
print("New breadth of the rectangle is \(myRectangle.breadth)")

Output:

Area of the rectangle is 50.0
Perimeter of the rectangle is 30.0
New length of the rectangle is 7.5
New breadth of the rectangle is 7.5

3. Step By Step Explanation

1. We start by defining a Rectangle struct with two stored properties: length and breadth.

2. We then define a computed property area that calculates and returns the area of the rectangle using the stored properties.

3. The perimeter computed property is slightly more advanced, as it includes both a getter (to get the perimeter) and a setter (to set new values to length and breadth based on the new perimeter).

4. We initialize an instance of the Rectangle struct named myRectangle with given dimensions.

5. We then print the area and perimeter using the respective computed properties.

6. Finally, we demonstrate the use of the setter in the perimeter computed property by assigning a new value. This changes the dimensions of the rectangle and we print the updated dimensions.


Comments