In this section, we will delve into the concepts of properties and methods in Swift. These are fundamental aspects of object-oriented programming (OOP) that allow you to define and manipulate the data and behavior of your classes and structures.

Properties

Properties are variables or constants that are associated with a class or structure. They store values and can be used to represent the state of an object.

Types of Properties

  1. Stored Properties: These are variables or constants that store values as part of an instance of a class or structure.
  2. Computed Properties: These do not store a value directly. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.
  3. Lazy Stored Properties: These are properties whose initial values are not calculated until the first time they are used.

Stored Properties

Stored properties can be either variables (var) or constants (let).

class Person {
    var name: String
    let birthYear: Int

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

let person = Person(name: "Alice", birthYear: 1990)
print(person.name) // Output: Alice

Computed Properties

Computed properties provide a getter and an optional setter.

class Rectangle {
    var width: Double
    var height: Double

    var area: Double {
        return width * height
    }

    init(width: Double, height: Double) {
        self.width = width
        self.height = height
    }
}

let rectangle = Rectangle(width: 5.0, height: 4.0)
print(rectangle.area) // Output: 20.0

Lazy Stored Properties

Lazy properties are initialized only when they are first accessed.

class DataLoader {
    lazy var data: [String] = {
        // Simulate a time-consuming data loading process
        return ["Data1", "Data2", "Data3"]
    }()
}

let loader = DataLoader()
print(loader.data) // Output: ["Data1", "Data2", "Data3"]

Methods

Methods are functions that are associated with a class, structure, or enumeration. They define the behavior of an object.

Instance Methods

Instance methods are functions that belong to an instance of a class, structure, or enumeration.

class Calculator {
    func add(a: Int, b: Int) -> Int {
        return a + b
    }
}

let calculator = Calculator()
print(calculator.add(a: 3, b: 5)) // Output: 8

Type Methods

Type methods are functions that are called on the type itself, rather than on an instance of the type. They are defined using the static keyword for structures and enumerations, and the class keyword for classes.

class Math {
    class func square(number: Int) -> Int {
        return number * number
    }
}

print(Math.square(number: 4)) // Output: 16

Practical Exercises

Exercise 1: Define a Class with Properties and Methods

Define a class Car with the following properties and methods:

  • Properties: make (String), model (String), year (Int)
  • Method: carDetails that returns a string with the car's details.

Solution:

class Car {
    var make: String
    var model: String
    var year: Int

    init(make: String, model: String, year: Int) {
        self.make = make
        self.model = model
        self.year = year
    }

    func carDetails() -> String {
        return "\(year) \(make) \(model)"
    }
}

let car = Car(make: "Toyota", model: "Corolla", year: 2020)
print(car.carDetails()) // Output: 2020 Toyota Corolla

Exercise 2: Create a Computed Property

Add a computed property age to the Car class that calculates the car's age based on the current year.

Solution:

class Car {
    var make: String
    var model: String
    var year: Int

    var age: Int {
        let currentYear = Calendar.current.component(.year, from: Date())
        return currentYear - year
    }

    init(make: String, model: String, year: Int) {
        self.make = make
        self.model = model
        self.year = year
    }

    func carDetails() -> String {
        return "\(year) \(make) \(model)"
    }
}

let car = Car(make: "Toyota", model: "Corolla", year: 2020)
print(car.age) // Output: 3 (assuming the current year is 2023)

Summary

In this section, we covered:

  • The different types of properties in Swift: stored, computed, and lazy stored properties.
  • How to define and use instance methods and type methods.
  • Practical exercises to reinforce the concepts of properties and methods.

Understanding properties and methods is crucial for mastering object-oriented programming in Swift. In the next section, we will explore inheritance, which allows classes to inherit properties and methods from other classes.

© Copyright 2024. All rights reserved