Subscripts in swift

Abhimuralidharan
2 min readMay 18, 2017

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].

// subscripting an array.. array = [1, 2, 3, 5, 8, 13]

print(array[0]) // prints 1


print(array[1..4]) // 1..4 is the range from 1 to 4 without 4
print(array[1...4]) // 1...4 is the range from 1 to 4 including 4
// subscripting a dictionary..
var
dictionary = ["male": "I am a male"]
print(dictionary["male"]) // prints "I am a male"

For a single type, subscripts can range from single to multiple declarations. We can use the appropriate subscript to overload the type of index value passed to the subscript.

Syntax: (This looks a lot like a Swift computed property.)

subscript (<parameters>) -> <return type> {
// the getter is required
get {
//…

--

--