Subscripts Explained in Swift
Swift subscripts are methods that allow you to access individual elements in a collection, list or sequence.
A subscript can be defined in a class, structure or enumeration, and the syntax is like a function that operates like a computed property.
Similar to a function, a subscript can accept parameters and return a value. The arguments are supplied in square brackets at the call site.
In the same way as a computed property, a subscript call is used to reference a property — so you can fetch its values or assign new values.
Let’s see how it works!
Subscript in Action
struct DayTemp {
private var temperatures: [String: Int] = [
"Monday": 70,
"Tuesday": 72,
"Wednesday": 68,
"Thursday": 75,
"Friday": 71,
"Saturday": 74,
"Sunday": 73
]
subscript(day: String) -> Int? {
get {
temperatures[day]
}
set(newTemp) {
if let temp = newTemp {
temperatures[day] = temp
}
}
}
}
var weekTemp = DayTemp()
if let mondayTemp = weekTemp["Monday"] {
print("Monday's temperature is \(mondayTemp)") // output: Monday's temperature is 70
}
weekTemp["Monday"] = 90
if let updateMondayTemp = weekTemp["Monday"] {
print("Monday's updated temperature is \(updateMondayTemp)") // output: Monday's updated temperature is 90
}
The code begins with the DayTemp structure, and it has a dictionary named temperatures that stores temperatures for each day of the week.
领英推荐
subscript(day: String) -> Int?
Here, a subscript is defined. It takes a String (day name) as an index and returns an optional Int? (temperature).
The get block allows you to read (access) the temperature for a given day.
The set block allows you to modify the temperature for a given day.
Using weekTemp["Monday"] lets you get Monday’s temperature.
To set a new temperature, you assign a new integer to the weekTemp (subscript), passing in the day of the week as an argument, like so: weekTemp[“Monday”] = 90.
Subscripts provide a way to make accessing or updating data in custom types more convenient and similar to array or dictionary syntax.