Swift Arrays

This chapter explores swift-arrays , a collection type that stores ordered, indexable elements of the same type. Arrays are a fundamental tool in Swift, enabling efficient data organization, manipulation, and retrieval.

Chapter Goals

  • Understand the purpose and characteristics of arrays in Swift.
  • Learn how to create, modify, and iterate over arrays.
  • Explore practical use cases for arrays.
  • Implement advanced operations using Swift array methods.

Key Characteristics of Swift Arrays

  • Ordered Collection: Elements are stored in a specific order.
  • Zero-Based Indexing: Elements are accessed using their position, starting from index 0.
  • Type-Safe: Elements must all be of the same type.
  • Dynamic Sizing: Arrays can grow or shrink dynamically.

Basic Rules for Arrays

  • Declare arrays using square brackets ([]).
  • Initialize arrays with or without elements.
  • Use let for immutable arrays and var for mutable arrays.
  • Ensure type compatibility for all elements.

Syntax Table

Serial No Feature Syntax/Example Description
1 Array Declaration let numbers = [1, 2, 3, 4] Creates an array with initial elements.
2 Empty Array var emptyArray: [Int] = [] Creates an empty array of integers.
3 Accessing Elements let first = numbers[0] Retrieves the first element of the array.
4 Modifying Elements numbers[0] = 10 Updates the first element of the array.
5 Iterating Arrays for number in numbers { print(number) } Loops through each element in the array.

Syntax Explanation

1. Array Declaration

What is Array Declaration?

Array declaration initializes an array with a set of elements.

Syntax

let numbers = [1, 2, 3, 4]

Detailed Explanation

  • Arrays are created using square brackets ([]).
  • The elements must be of the same type.
  • Use let for immutable arrays and var for mutable arrays.

Example

let fruits = [“Apple”, “Banana”, “Cherry”]

print(fruits)

Example Explanation

  • Declares an array fruits with three string elements.
  • Prints the array to the console.

2. Empty Array

What is an Empty Array?

An empty array contains no elements and is useful for dynamic population.

Syntax

var emptyArray: [Int] = []

Detailed Explanation

  • Use square brackets with a type annotation to define an empty array.
  • Use var to allow adding elements later.
  • The type must be specified explicitly if the array is empty at initialization.

Example

var scores: [Int] = []

scores.append(100)

print(scores)

Example Explanation

  • Declares an empty array scores of integers.
  • Adds an element using the append method.
  • Prints the updated array containing one element.

3. Accessing Elements

What is Accessing Elements?

Accessing elements retrieves specific items from an array using their index.

Syntax

let first = numbers[0]

Detailed Explanation

  • Use the index inside square brackets to access an element.
  • Indexing starts at 0 for the first element.
  • Ensure the index is within bounds to avoid runtime errors.

Example

let colors = [“Red”, “Green”, “Blue”]

let favoriteColor = colors[1]

print(favoriteColor)

Example Explanation

  • Declares an array colors with three string elements.
  • Retrieves the second element (“Green”) using its index.
  • Prints the retrieved element.

4. Modifying Elements

What is Modifying Elements?

Modifying elements updates the value of specific items in a mutable array.

Syntax

numbers[0] = 10

Detailed Explanation

  • Use the index and assignment operator to update an element.
  • The array must be declared with var to allow modifications.

Example

var temperatures = [30, 25, 20]

temperatures[2] = 18

print(temperatures)

Example Explanation

  • Declares a mutable array temperatures.
  • Updates the third element to 18.
  • Prints the modified array.

5. Iterating Arrays

What is Iterating Arrays?

Iterating arrays processes each element sequentially using a loop.

Syntax

for number in numbers { print(number) }

Detailed Explanation

  • Use a for loop to traverse each element in the array.
  • Access the current element within the loop body.
  • Enables processing or displaying all elements efficiently.

Example

let animals = [“Cat”, “Dog”, “Elephant”]

for animal in animals {

    print(“Animal: \(animal)”)

}

Example Explanation

  • Declares an array animals with three string elements.
  • Iterates through each element and prints its value with a prefix.

Real-Life Project: Student Grades Tracker

Project Goal

Create a program to store and manage student grades using arrays.

Code for This Project

struct GradeTracker {

    var grades: [Int]




    mutating func addGrade(_ grade: Int) {

        grades.append(grade)

    }




    func calculateAverage() -> Double {

        let total = grades.reduce(0, +)

        return Double(total) / Double(grades.count)

    }




    func displayGrades() {

        print("Grades: \(grades)")

    }

}




var tracker = GradeTracker(grades: [85, 90, 78])

tracker.addGrade(92)

tracker.displayGrades()

let average = tracker.calculateAverage()

print("Average Grade: \(average)")

Steps

  1. Define a GradeTracker struct with a grades property.
  2. Implement methods to add grades, calculate averages, and display grades.
  3. Test the program with sample grades.

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 real-world use of arrays.
  • Validates dynamic data handling and calculations.
  • Provides immediate feedback for array operations.

Best Practices

Why Use Arrays?

  • Efficiently store and access multiple values.
  • Enable organized and indexed data management.
  • Support dynamic resizing for flexible data handling.

Key Recommendations

  • Use let for fixed arrays and var for dynamic arrays.
  • Validate index bounds before accessing elements.
  • Leverage array methods like append, remove, and filter for streamlined operations.

Example of Best Practices

var shoppingList = [“Milk”, “Eggs”, “Bread”]

shoppingList.append(“Butter”)

shoppingList.remove(at: 1)

print(shoppingList)

Insights

Arrays in Swift are powerful and versatile, providing a structured way to manage ordered data. Their dynamic nature makes them suitable for a wide range of applications.

Key Takeaways

  • Arrays are ordered collections with zero-based indexing.
  • Use array methods for efficient and dynamic data manipulation.
  • Arrays simplify data storage, access, and iteration in Swift.