What is Object-Oriented Programming (OOP) properties in swift?

 What is Object-Oriented Programming (oop) properties in swift?



In Swift, Object-Oriented Programming (OOP) defines classes and objects that encapsulate data and behavior. The properties in Swift's OOP are the variables and constants that determine the attributes of a class or object.


Properties are defined within a class and are used to store data or values that can be accessed by instances of that class. They can be defined as variables or constants and have an initial value or be set at runtime.


There are two types of properties in Swift's OOP: stored properties and computed properties.


Stored properties are variables or constants that store a value or reference. They can be defined with an initial value or left uninitialized to be set later. They are declared using the var or let keyword, depending on whether they are mutable or immutable.


Here is an example of a stored property in Swift:


1
2
3
4
5
6
7
8
9
class Person {
    var name: String
    let age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}


In this example, the Person class has two stored properties: name and age. The name property is a variable because it can be changed, while the age property is a constant because it should not change after it is set in the init method.


Computed properties are variables that do not store a value directly but instead provide a getter and a setter to calculate or retrieve the value. They are declared using the var keyword with a get and set block that defines the logic for calculating or setting the value.

 

Here is an example of a computed property in Swift:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Circle {
    var radius: Double

    var area: Double {
        get {
            return Double.pi * radius * radius
        }
        set {
            radius = sqrt(newValue / Double.pi)
        }
    }

    init(radius: Double) {
        self.radius = radius
    }
}


In this example, the Circle class has a computed property called the area, which calculates the area of the circle based on its radius. The area property has a getter that returns the calculated value and a setter that sets the radius based on the area value.


In conclusion, properties in Swift's OOP are variables and constants that define the attributes of a class or object. They can be stored properties that store a value directly or computed properties that calculate or retrieve a value through a getter and setter. Understanding properties is an essential part of mastering Swift's OOP.


My Linkedin: https://www.linkedin.com/company/systemapps



buymeacoffee: https://www.buymeacoffee.com/ShahriarDev

 

Comments

Popular posts from this blog

What Was Blogging Like Before and After AI?

Is SwiftUI better than Flutter?