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.
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.
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])
get
and set
method to create a sample object.RELATED TAGS
CONTRIBUTOR
View all Courses