Swift Subscripts Example

1. Introduction

Subscripts are shortcuts for accessing the member elements of a collection, list, sequence, or other grouping type. They allow classes, structures, and enumerations to define and expose their functionality using subscript syntax. Instead of invoking a method, you use index values inside square brackets to set and retrieve values.

2. Source Code Example

// Define a structure for a simple 'Day' storage
struct Week {
    private var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

    // Subscript definition for Week structure
    subscript(index: Int) -> String {
        get {
            // Return the day at the specified index
            return days[index]
        }
        set(newValue) {
            // Update the day at the specified index with the new value
            days[index] = newValue
        }
    }
}

// Create an instance of the Week structure
var myWeek = Week()

// Accessing days using the defined subscript
print("The first day of the week is: \(myWeek[0])")  // Using the subscript to get the value

// Modify the first day of the week using subscript
myWeek[0] = "Funday"
print("After changing, the first day of the week is: \(myWeek[0])")

Output:

The first day of the week is: Sunday
After changing, the first day of the week is: Funday

3. Step By Step Explanation

1. We define a Week struct which internally has an array days that stores names of the days of the week.

2. Within the Week struct, a subscript is defined. This subscript allows for the setting and retrieval of days using an index.

3. The get property inside the subscript is used to retrieve the value of a specific day using its index.

4. The set property allows us to set a new value for a specific day using its index.

5. We then initialize an instance of the Week struct named myWeek.

6. Through subscripting, we can both retrieve and modify days in the myWeek instance. In the example, we first retrieve the name of the day at index 0 (which is Sunday), and then we modify its value to "Funday".


Comments