Swift Programming – Subscripts

In this tutorial you’ll learn about subscripts in Swift. To follow along, it is recommended to have a Mac and the Xcode IDE installed on it. This tutorial makes use of the Xcode playground for compilation of the Swift codes. If you do not have a Mac, you may try using the open-source code editors which support different operating systems such as AtomSublimeText or VSCode.

Subscripts

Subscript is a way of setting and retrieving values to/from a collection type. Recall in our lesson on Swift Programming – Collection Types, we used the subscript syntax for setting and retrieving values to/from arrays and dictionaries. We can define multiple subscripts in a class, structure and enumeration. Let’s refresh our memory with an example of using the subscript syntax in an array.

var groceries = ["Fruits", "Vegetables", "Tea", "Coffee"]
// using subscript syntax to set a new value to the first item
groceries[0] = "Fruit"

// using subscript syntax to retrieve the first item
print("first item is \(groceries[0])")

Subscript Syntax

A subscript definition syntax is like an instance method syntax and a computed property syntax combined. Like a computed property syntax, a subscript definition syntax can either be read-write or read-only. The following examples demonstrate the syntax of a subscript definition as read-write and as read-only.

// read-write
subscript(index: Int) -> Int {
    get { // return a subscript value }
    set { // perform some operation on the newValue } // or set(newValue) { }
}

// read-only
subscript(index:Int) -> Int {
    // return a subscript value 
}

Let’s try an example using the subscript definition syntax in a structure.

enum ArithmeticOperator {
    case addition, subtraction, multiplication, division
}

struct MathOperation {
    let operand: Int
    let arithmeticOperator: ArithmeticOperator
    
    subscript(index: Int) -> Int {
        switch(arithmeticOperator) {
        case .addition:
            return operand + index
        case .subtraction:
            return operand - index
        case .multiplication:
            return operand * index
        case .division:
            return Int(Double(operand) / Double(index))
        }
    }
}

var mathOperation = MathOperation(operand: 15, arithmeticOperator: ArithmeticOperator.addition)
print(mathOperation[5])
mathOperation = MathOperation(operand: 60, arithmeticOperator: ArithmeticOperator.division)
print(mathOperation[5])

Type Subscripts

So far we tried an example of an instance subscript. Recall in our lesson Swift Programming – Methods, we explore the two different types of methods, instance methods and type methods. Similarly, for subscripts we have instance subscripts and type subscripts. Let’s try an example with a type subscript.

enum DayOfWeek: Int {
    case Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
    
    static subscript(index: Int) -> DayOfWeek {
        return DayOfWeek(rawValue: index) ?? .Monday
    }
}

let friday = DayOfWeek[5]
print(friday)

Reference

https://docs.swift.org/swift-book/LanguageGuide/Subscripts.html

Advertisement