Swift Structures

This chapter explores swift-structures , a foundational concept for creating custom data types. Structures, or structs, provide a way to group related properties and methods, enabling developers to model real-world entities efficiently. Unlike classes, structures are value types, making them lightweight and ideal for certain use cases.

Chapter Goals

  • Understand what structures are and their role in Swift programming.
  • Learn how to define and use structures.
  • Explore advanced features like initializers, computed properties, and methods.
  • Implement real-world examples using structures.

Key Characteristics of Swift Structures

  • Value Type: Structures are copied when assigned or passed.
  • Encapsulation: Combine properties and methods into a single type.
  • Efficient and Lightweight: Ideal for scenarios requiring immutable or localized data.
  • Custom Initializers: Automatically generate memberwise initializers.
  • Protocol Conformance: Structures can adopt and conform to protocols.

Basic Rules for Structures

  • Use the struct keyword to define a structure.
  • Structures can contain properties, methods, and initializers.
  • Support immutability when declared with let.
  • Use structures for data that needs copying instead of sharing.

Syntax Table

Serial No Feature Syntax/Example Description
1 Structure Declaration struct StructName { … } Declares a new structure.
2 Property Declaration var propertyName: Type Defines a property within a structure.
3 Method Declaration func methodName() { … } Defines a function within a structure.
4 Initializer init(parameters) { … } Sets up an instance upon creation.
5 Mutating Method mutating func methodName() { … } Modifies properties of a structure.

Syntax Explanation

1. Structure Declaration

What is a Structure Declaration?

A structure declaration defines a custom data type that groups related properties and methods.

Syntax

struct Person {

    var name: String

    var age: Int

}

Detailed Explanation

  • Use the struct keyword followed by the structure name.
  • Define properties and methods within curly braces ({}).
  • Structures are value types, meaning they are copied when passed or assigned.

Example

let person = Person(name: “Alice”, age: 25)

print(person.name)

 

Example Explanation

  • Declares a Person structure with two properties.
  • Creates an instance of Person and accesses its name property.

2. Property Declaration

What is a Property Declaration?

Properties store values specific to each instance of a structure.

Syntax

var propertyName: Type

 

Detailed Explanation

  • Properties can be variables (var) or constants (let).
  • Store instance-specific data for each structure.
  • Can have default values or be set during initialization.

Example

struct Car {

    var make: String

    var model: String

    var year: Int = 2024

}

 

let car = Car(make: “Tesla”, model: “Model S”)

print(“\(car.make) \(car.model), \(car.year)”)

 

Example Explanation

  • Declares a Car structure with three properties.
  • Uses a default value for year while initializing make and model.

3. Method Declaration

What is a Method Declaration?

Methods define actions or behaviors for a structure.

Syntax

func methodName() { … }

 

Detailed Explanation

  • Methods are functions defined inside a structure.
  • Can access and manipulate the structure’s properties.
  • Cannot modify properties unless marked with mutating.

Example

struct Rectangle {

    var width: Double

    var height: Double

 

    func area() -> Double {

        return width * height

    }

}

 

let rectangle = Rectangle(width: 10, height: 20)

print(rectangle.area())

 

Example Explanation

  • Declares a Rectangle structure with a method to calculate area.
  • Computes and prints the area using the area method.

4. Initializer

What is an Initializer?

An initializer sets up a structure’s properties when an instance is created.

Syntax

init(parameters) { … }

 

Detailed Explanation

  • Use init to define custom initialization logic.
  • Assign values to properties during instantiation.
  • Swift automatically provides a memberwise initializer if no custom initializer is defined.

Example

struct Circle {

    var radius: Double

 

    init(radius: Double) {

        self.radius = radius

    }

 

    func circumference() -> Double {

        return 2 * .pi * radius

    }

}

 

let circle = Circle(radius: 5)

print(circle.circumference())

 

Example Explanation

  • Declares a Circle structure with a custom initializer.
  • Computes and prints the circumference.

5. Mutating Method

What is a Mutating Method?

A mutating method modifies the properties of a structure.

Syntax

mutating func methodName() { … }

 

Detailed Explanation

  • Structures are immutable by default when declared with let.
  • Use mutating to allow methods to modify properties.
  • Changes made within a mutating method persist across calls.

Example

struct Counter {

    var count: Int = 0

 

    mutating func increment() {

        count += 1

    }

}

 

var counter = Counter()

counter.increment()

print(counter.count)

 

Example Explanation

  • Declares a Counter structure with a mutating increment method.
  • Increments the count property and prints the updated value.

Real-Life Project: Expense Tracker

Project Goal

Create an expense tracker to manage financial transactions using structures.

Code for This Project

struct Expense {

    var description: String

    var amount: Double




    func display() {

        print("\(description): $\(amount)")

    }

}




struct ExpenseTracker {

    var expenses: [Expense] = []




    mutating func addExpense(_ expense: Expense) {

        expenses.append(expense)

    }




    func totalExpenses() -> Double {

        return expenses.reduce(0) { $0 + $1.amount }

    }




    func displayExpenses() {

        for expense in expenses {

            expense.display()

        }

    }

}




var tracker = ExpenseTracker()

tracker.addExpense(Expense(description: "Groceries", amount: 50.0))

tracker.addExpense(Expense(description: "Utilities", amount: 100.0))

tracker.displayExpenses()

print("Total: $\(tracker.totalExpenses())")

Steps

  1. Define an Expense structure with properties for description and amount.
  2. Create an ExpenseTracker structure to manage multiple expenses.
  3. Implement methods to add and display expenses, and calculate the total.
  4. Test the tracker with sample data.

Save and Run

Steps to Save and Run

  1. Write the code in your Swift IDE (e.g., Xcode).
  2. Save the file using Command + S (Mac) or the appropriate save command.
  3. Click “Run” or press Command + R to execute the program.

Benefits

  • Demonstrates encapsulation and method usage.
  • Highlights the use of structures for lightweight data management.
  • Provides a practical application for structures in finance tracking.

Best Practices

Why Use Structures?

  • Ideal for lightweight and immutable data.
  • Promote code clarity and modular design.
  • Simplify development with automatic memberwise initializers.

Key Recommendations

  • Use let for immutable instances to prevent unintended changes.
  • Leverage mutating methods sparingly for controlled modifications.
  • Conform to protocols for standardized behavior.

Example of Best Practices

struct User {

    var name: String

    var age: Int

 

    func greet() {

        print(“Hello, \(name), age \(age).”)

    }

}

 

let user = User(name: “Alice”, age: 30)

user.greet()

 

Insights

Swift structures provide a powerful yet lightweight way to encapsulate related data and behavior. By leveraging value semantics and built-in features, developers can design efficient and reliable applications.

Key Takeaways

  • Structures are value types ideal for localized and immutable data.
  • Use methods, properties, and initializers to define behavior and state.
  • Mutating methods enable controlled modification of properties when needed.