Greetings, traveler!
A subscripts provides us with a convenient tool to access collection, list, or sequence elements. For example, you have encountered them when using arrays and dictionaries. You can both retrieve an element and set or add a new value.
var array = ["String"]
let element = array[0]
array[0] = ""
var dict = [0: "String"]
let value = dict[0]
dict[0] = ""
Custom subscripts
You can create your own way to use this tool. Consider this example. Create a class DataSource, which holds an array of optional strings. If you mark this property with the private keyword, you won’t be able to retrieve a value from this array without creating an additional method. Like this:
final class DataSource {
var names: [String?] = ["Samuel", "Frank", "Kate"]
func getName(by index: Int) -> String? {
names[index]
}
}
let dataSource = DataSource()
let element = dataSource.getName(by: 0)
But you can make your code a bit cleaner using subscripts.
final class DataSource {
var names: [String?] = ["Samuel", "Frank", "Kate"]
subscript(index: Int) -> String? {
names[index]
}
}
let dataSource = DataSource()
let element = dataSource[0]
You can also add a new value with subscript. To do this, we will need to use a getter and a setter.
final class DataSource {
var names: [String?] = ["Samuel", "Frank", "Kate"]
subscript(index: Int) -> String? {
get {
names[index]
}
set {
names[index] = newValue
}
}
}
let dataSource = DataSource()
dataSource[0] = "John"
Static subscripts
You can use static subscripts in the same way. Consider this example.
enum DataSource {
static var names: [String?] = ["Samuel", "Frank", "Kate"]
static subscript(index: Int) -> String? {
get {
names[index]
}
set {
names[index] = newValue
}
}
}
DataSource[1] = ""
Note
You can also use subscripts with the @dynamicMemberLookup keyword and Key paths. This is a very cool Swift feature. You can read more about it here.
Conclusion
Subscripts is a convenient tool that can help you make your code cleaner and more obvious.