In Swift, subscripts are shortcuts for accessing specific elements within a collection, sequence or list. These are basically methods which are written using the subscript keyword. Similar to how an array uses indexing to access its elements, a subscript allows an object to be accessed using the same syntax as in an array. In this tutorial, we will see how to implement subscripts in Swift.
Subscripts are implemented with one or more parameters and return a value of some type, either read-only or read-write. Here's a simple example of implementing a subscript for a class:
class Player {
subscript(index: Int) -> String {
get {
return "Player\(index)"
}
set(newValue) {
print("New value \(newValue) is assigned to Player\(index)")
}
}
}
let player = Player()
print(player[5]) // Output: Player5
player[2] = "John" // Output: New value John is assigned to Player2
In the above example, we implemented a subscript for the Player class which allows us to access the player names using an integer index. In the get block of the subscript, we return the string representation of the player name based on the passed index. The set block is used to update the player name based on a new value. Here, the subscript allows us to update the player name by simply assigning a new value to the subscript index.
Subscripts can also be used with mutable and immutable properties in Swift. Here's an example of implementing subscripts with a Dictionary:
struct StudentMarks {
var marks = ["Maths": 75, "Physics": 87, "Chemistry": 92]
subscript(subject: String) -> Int {
get {
guard let mark = marks[subject] else {
return -1 // Return -1 if subject not found
}
return mark
}
set(newMark) {
marks[subject] = newMark
}
}
}
var student = StudentMarks()
print(student["Physics"]) // Output: 87
student["Maths"] = 85
print(student["Maths"]) // Output: 85
print(student["Biology"]) // Output: -1
Here, we implemented a subscript for the StudentMarks struct that allows us to get and set the marks of a particular subject as needed. In the get block of the subscript, we check whether the subject is present in the marks dictionary property or not. If it is present, we return the corresponding mark, otherwise we return -1. In the set block, we update the dictionary with the new mark value passed.
Subscripts in Swift are a shorthand for accessing elements in a collection, sequence or list. They allow us to access and manipulate the object in the same way as accessing an array. By implementing subscripts in our classes, structs or enums, we can simplify the syntax of accessing and updating values stored within them.