Subscript Syntax In Swift Explained

Written by Reinder de Vries on February 8 2019 in App Development

Subscript Syntax In Swift Explained

With subscripts you can quickly access the member elements of collections. It’s a powerful feature of the Swift programming language. In this article, you’ll learn how to use subscript syntax and how to define your own custom subscripts.

Ready? Let’s go.

  1. What’s A Subscript?
  2. When Are Subscripts Useful?
  3. Creating Your Own Custom Subscripts
  4. Further Reading

What’s A Subscript?

It’s easiest to understand what a subscript is by using an example. Check out this dictionary:

var scores = [
    "arthur": 42,
    "ford": 99
    "trillian": 314
]

The above dictionary scores has keys of type String and values of type Int. You could say that it associates person names with a score, i.e. Arthur has scored 42 points. You can now refer to any of the members in this collection by using subscript syntax.

You get a value like this:

let arthurScore = scores["arthur"]
print(arthurScore)
// Output: 42

And set a value, like this:

scores["arthur"] = 101
print(scores["arthur"])
// Output: 101

The scores["arthur"] part is called subscript syntax. It’s the Swift syntax you need to access member elements of the scores dictionary.

A subscript consists of:

  • The name of the collection, such as scores
  • Two square brackets [ and ]
  • A key or index inside the brackets

By default, you can use subscripts with arrays, dictionaries, collections, lists and sequences. You can also implement your own with the subscript function, as you’ll see later on.

Subscripting isn’t limited to a single dimension, which means you can use them for multi-dimensional arrays and dictionaries too.

Take this 2×2 matrix, for instance:

let matrix = [
    [0, 1],
    [3, 0]
]

We can now access the value 3, like this:

let value = matrix[1][0]
print(value)
// Output: 3

In the above code matrix[1][0], we’re using two subscripts successively:

  • [1] is used to get the array [3, 0] from the array matrix
  • [0] is used to get the integer 3 from the array [3, 0]

If you’re unfamiliar with arrays, it’s worth reading up on them. Keep in mind that the arrays are zero-indexed, so they start at index number 0.

Give it a try, to see exactly what you’re getting:

let matrix = [
[0, 1],
[3, 0]
]

print(matrix[1])
print(matrix[1][0])

When Are Subscripts Useful?

Subscripts are useful in a great number of scenarios, especially because they make your code concise and easy to read.

Consider the Address Book below. Imagine it’s full of names and addresses.

let contacts = [
    ...
    "Arthur Dent": [
        "address": [
            "street": "Infinite Drive 101",
            "postcode": "ABCD12",
            "city": "London"
        ],
        "planet": "Sector ZZ9 Plural Z Alpha",
        "designation": "Mostly Harmless"
        "phone": "+1 1234 56 7890"
    ],
    ...
]

A great way to “navigate” to a street address, is this:

let street = contacts["Arthur Dent"]["address"]["street"]
print(street)
// Output: Infinite Drive 101

That’s expressive — get the member with key "Arthur Dent", then get its address with key ["address"], and then get the value of key "street".

It’s important to understand here that the first subscript essentially gets the entire contact entry, and the second gets the "address" collection from that complete entry, and the third gets the String value with the streetname.

You can see it as branches on a tree, if you “rotate” the collection counter-clockwise. Every [...] refers to a branch, until you get to the “leaf”, i.e. the value you’re looking for.

You can also use expressions as keys or indices, such as variables and constants. Check this out:

let pi = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]

for index in 0..<pi.count
{
let digit = pi[index]

print("\(index+1)nth digit of Pi = \(digit)")
}

In the above code we’re defining an array with digits of the number Pi (3.1415). The for loop iterates over a range from 0 to the end of the array, with 0..<pi.count.

On the first line of the for loop, pi[index] is used to access a member of the pi array with a given index number. Because of the loop, this index corresponds to every possible index number in the pi array.

Finally, we’re printing out the result:

1nth digit of Pi = 3
2nth digit of Pi = 1
...
10nth digit of Pi = 3

Note: Arrays in Swift are zero-indexed, so we’re using index+1 to write the right ordinal number. Otherwise it would say “0th digit of …”

Creating Your Own Custom Subscripts

You can define your own subscripts with the subscript keyword. Here’s an example:

class Database 
{
    subscript(index: Int) -> Object {
        get {
            return database.get(index)
        }
        set(newValue) {
            database.set(index, newValue)
        }
    }
}

Imagine we’re building a database system, that uses some kind of on-disk saving method. You want to access this database like any other collection, so you define the above subscript function.

You can now read and write from the database like this:

let data = Database()
let entry = data[999]
print(entry)

data[123] = "<<<some data>>>"

A real-world example can be found in the source code of Realm, a database platform. If you scroll down (or search) in Results.swift, you can see the subscript and how it returns an object of type Element from rlmResults. Because of this, you can use Results[index] in your own Swift project.

What’s even more interesting is that any class can define a subscript, even if that class isn’t a typical collection. In that sense, the subscript syntax just calls a function.

Here, check this out:

class Count
{
subscript(index: Int) -> String
{
switch index {
case 0: return "zero"
case 1: return "one"
case 2: return "two"
default: return "many"
}
}
}

let count = Count()
print(count[1])
print(count[99])

Hmm, that’s interesting! Even though the Count class isn’t a collection, you can use it like a collection by accessing any key with subscript syntax.

The Int index is just used as the input for the subscript function, which returns a string based on the number by using a switch block. Amazing!

Further Reading

In essence, subscripts are just syntactic sugar to access members of collections. It’s quite powerful though, and concise, and it’s always a great idea to dive a little deeper into such syntactic niceties. After all, you learn a great deal about Swift programming this way.

If you’re up for a challenge, check out Playing With Code: Insertion Sort In Swift. The implementation of the insertion sort relies on subscripts to get the right values from the sorting array – so it’s good practice to get the hang of how subscripts and arrays work.

Want to learn more? Check out these resources:

Learn how to build iOS apps

Get started with iOS 12 and Swift 5

Sign up for our iOS development course Zero to App Store and learn how to build professional iOS 12 apps with Swift 5 and Xcode 10.

Reinder de Vries

Reinder de Vries

Reinder de Vries is a professional iOS developer. He teaches app developers how to build their own apps at LearnAppMaking.com. Since 2009 he has developed a few dozen apps for iOS, worked for global brands and lead development at several startups. When he’s not coding, he enjoys strong espresso and traveling.