In this tutorial you will learn about the Swift Subscripts and its application with practical example.
Swift Subscripts
In Swift, subscripts are used to retrieve any specific information from a collection, list, or sequence without using a method. With the help of subscripts we can store and retrieve the values directly using associated index.
Defining Subscripts In Swift
In swift, general syntax to declare a subscript is very similar with syntax to declare instance method and computed property. You need use subscript keyword followed by parameter list and a return type, in the subscript body there is a getter and a setter properties to define whether subscript is a read-write or ready-only.
Syntax:-
1 2 3 4 5 6 7 8 |
subscript(parameterList) -> ReturnType { get { // return someValue } set (newValue) { // set someValue } } |
Syntax for read only:-
1 2 3 |
subscript(parameterList) -> ReturnType { } |
Example:-
1 2 3 4 5 6 7 8 9 |
struct addition{ let sum: Int subscript(i: Int) -> Int { return sum + i } } let sum = addition(sum: 45) print("W3Adda - Swift Subscript Read Only") print("Subscript Value of: \(sum[5])") |
Output:-
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class daysOfWeek { 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 dow = daysOfWeek() print("W3Adda - Swift Subscript") print(dow[0]) print(dow[1]) print(dow[2]) print(dow[3]) print(dow[4]) print(dow[5]) print(dow[6]) |
Output:-
Swift Subscripts Options
Subscripts are allowed to take one or more parameters of any data type and subscripts does not support default parameter values.In swift we can provide multiple subscripts for a class or structure based on requirement, it is known as “subscript overloading”.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
class employee { var paramOne: String? var paramTwo: String? subscript(row: Int, col: Int) -> String { get { if row == 0 { if col == 0 { return paramOne! } else { return paramTwo! } } return paramTwo! } set { if row == 0 { if col == 0 { paramOne = newValue } else { paramTwo = newValue } } } } } var emp = employee() print("W3Adda - Swift Subscripts Options") emp[0,0] = "John" emp[0,1] = "Alex" print(emp[0,0]) print(emp[0,1]) |
Output:-