Ans :
Subscripts are used to access information from a collection, sequence and a list in Classes, Structures and Enumerations without using a method.
These subscripts are used to store and retrieve the values with the help of index without the use of separate method.
To access elements via subscripts write one or more values between square brackets after the instance name.
For example: Array elements are accessed with the help of someArray[index] and its subsequent member elements in a Dictionary instance can be accessed as someDicitonary[key].
Code :
In coding, subscript is same as computed property.
If you have any comment, question, or recommendation, feel free to post them in the comment section below!
Subscripts are used to access information from a collection, sequence and a list in Classes, Structures and Enumerations without using a method.
These subscripts are used to store and retrieve the values with the help of index without the use of separate method.
To access elements via subscripts write one or more values between square brackets after the instance name.
For example: Array elements are accessed with the help of someArray[index] and its subsequent member elements in a Dictionary instance can be accessed as someDicitonary[key].
Code :
In coding, subscript is same as computed property.
class monthsInYear {
private var months = [“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, "Aug", "Sep" , "Oct", "Nov" , "Dec"]
subscript(index: Int) -> String {
get {
return months[index] // getter is mandatory
}
set(newValue) {
self.months[index] = newValue // setter is optional
}
}
}
var p = monthsInYear()
print(p[0]) // prints Jan
p[0] = “Jan”
print(p[0]) // prints Jan
If you have any comment, question, or recommendation, feel free to post them in the comment section below!
No comments:
Post a Comment
Thanks