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 {
// used for subscript value declarations
}
set(newValue) { // the setter is optional
// definitions are written here
}
}

The parameter list can take multiple values. The getter method id required. The setter method is optional. The parameter newValue in the setter method is implicitly declared. You can change it to anything you want which will improve the readability of the code.

Example:

class daysofaweek {private var days = [“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “saturday”]subscript(index: Int) -> String {
get {
return days[index]
}
set(newValue) {
self.days[index] = newValue
}
}
}
var p = daysofaweek()print(p[0]) // prints sundayp[0] = “Monday”print(p[0]) // prints Monday

Here is another example from Tutorialspoint.com

struct subexample {
let decrementer: Int
subscript(index: Int) -> Int {
return decrementer / index
}
}
let division = subexample(decrementer: 100)

print("The number is divisible by \(division[9]) times")
print("The number is divisible by \(division[2]) times")

it prints:

The number is divisible by 11 times
The number is divisible by 50 times

Enjoy!!

If you enjoyed reading this post, please share and recommend it so others can find it 💚💚💚💚💚💚 !!!!

--

--