Subscripts

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
August 5, 2023

Title: Subscripts in Swift

In Swift, subscripts are used to provide convenient access to elements in a collection or sequence, such as arrays, dictionaries, and custom types. Subscripts enable us to access values by using index values or keys.

Defining a Subscript

To define a subscript, we use the 'subscript' keyword followed by a parameter list, similar to a function. The subscript must be declared in a type, and can be either read-only or read-write.

Here's an example of a read-only subscript in a custom class:

class MyArray {
    private var array: [Int] = [1, 2, 3, 4, 5]
    
    subscript(index: Int) -> Int {
        return array[index]
    }
}

let myArray = MyArray()
let value = myArray[2] // Accessing element at index 2
print(value) // Output: 3

In the example above, we define a subscript in the 'MyArray' class that takes an 'Int' parameter (index) and returns an 'Int' value. When we create an instance of 'MyArray' and access elements using subscript notation, the subscript implementation is called, and the corresponding value is returned.

Read-Write Subscripts

We can also define read-write subscripts that allow modification of the accessed values.

class MyDictionary {
    private var dictionary: [String: String] = ["name": "John", "age": "25"]
    
    subscript(key: String) -> String? {
        get {
            return dictionary[key]
        }
        set {
            dictionary[key] = newValue
        }
    }
}

var myDictionary = MyDictionary()
myDictionary["name"] = "Alice" // Updating the value for the key "name"
let name = myDictionary["name"] // Accessing the updated value
print(name) // Output: Optional("Alice")

In the example above, the 'MyDictionary' class defines a read-write subscript that takes a 'String' parameter (key) and returns an optional 'String'. When we assign a new value using subscript notation, the 'set' block is executed, allowing us to update the value associated with the given key.

Conclusion

Subscripts in Swift provide a concise way to access elements in collections or sequences. They allow for clean and intuitive syntax, enhancing the usability and readability of our code when dealing with indexing and key-based access. By defining subscripts, we can make our custom types behave similarly to built-in types.