What are subscripts in Swift?
Overview
In Swift, we use the subscripts to access elements of a collection (sequence, lists, tuples, and dictionaries). Other features classes and enums are also carried out with subscripts. We can also carry out value placement and retrieval by providing the index in the subscript of a collection; in the case of a dictionary, a key value is provided in the subscript to access an element.
Syntax
These subscripts act like computed properties. To use a subscript with an instance, we use the square brackets [] with the instance name. The syntax of the subscript is the same as the computed property syntax. The subscript keyword defines subscript with parameters and single or multiple return values. Subscript could be restricted to the read-write or only-read property by utilizing the setter and getter subscript methods.
Example
class course {private var coursesName = ["Android", "IOS", "Web", "Machine Learning","AI", "DevOps", "Project Management"]subscript(index: Int) -> String {get {return coursesName[index]}set(newVal) {self.coursesName[index] = newVal}}}var courses = course()print(courses[0])print(courses[1])print(courses[2])print(courses[3])
Explanation
- Line 4: We define the subscript as the computed property.
- Lines 5–8: We use the
getandsetmethod to create a sample object. - Line 13: The sample object shows the working of the class course with a subscript in lines 15 to 18.
Free Resources