Swift Programming Tutorial: Subscripts
Quickly Understand What Subscripts Are
Imagine you’re watching a sci-fi movie where characters can instantly teleport anywhere on Earth by just thinking of a place. In Swift, subscripts are like that teleportation: they give you a quick way to access and modify elements in your data structure, like arrays, dictionaries, or even custom types that you make yourself.
This article is part of my Swift Programming Tutorial series. If you’re just beginning to learn Swift programming, make sure you understand collections first.
When you type something like array[0]
, you’re actually using a subscript. Swift automatically gives arrays and dictionaries this superpower so that you can access items by index or key. But here’s the fun part: you can create your own subscripts for any class, struct, or enum, so that your custom types can join the []
club!
Why Do You Need Subscripts?
Imagine you create a Library
struct that represents a library with a collection of books. Without a subscript, every time you wanted to find a book, you’d have to write a function like getBookByTitle(title: "1984")
. To some, it’s boring. Wouldn’t it be nice if you could just write library["1984"]
and get the book instantly?