Swift Subscripts

  Total Views : 162
  Comments : 0
  Keywords : Swift subscripts are the shortcuts to access elements of list or collection, Swift subscripts are useful to set and retrieve elements in collection by using index

Here we will learn subscripts in swift and how to use swift subscripts in classes, structures and enumerations with examples and different type of subscript options in swift with examples.

Swift Subscripts

In swift, subscript is a shorter way to access the elements in an arraydictionaries and etc. We can define the subscripts in classesstructures and enumerations. Using subscripts, we can directly access or set the value by using index without need of any special methods. 

 

By using subscripts we can call specific member of array instance like ArrayName[index] same way we can access the elements in dictionary instance like DictionaryName[index].

 

In swift we can define multiple subscripts for a single type and we can use appropriate subscript to overload the type of index value passed to the subscript. We can define subscripts to accept multiple input parameters based on our requirements.

Swift Subscripts Syntax

Generally, in swift subscript syntax will be same as instance method syntax and computed property syntax. To define subscript in swift we use subscript keyword and specify one or more input parameters and return type based on our requirements.

 

Following is the syntax of defining subscripts in swift programming language.

 

subscript(parameterName:datatype) -> ReturnType {

get {

// return value

}

set (newValue) {

// set value

}

}

If you observe above subscript syntax we used subscript keyword, input parameter and return type. We used getter & setter properties to define whether subscript is read-write or ready-only. 

 

The type of newValue must be same as return value of subscript and we have an option not to specify setter parameter (newValue) value. In that case the default parameter called newValue will be provided to setter.

 

In case if we want to define read-only subscript in swift, we need to remove getter and setter properties like as shown below syntax.

 

subscript(parameterName:datatype) -> ReturnType {

// set appropriate value

}

Now we will see how to create and use subscripts in swift programming language with examples.

Swift Subscripts Example

Following is the example of defining read-only subscript and accessing the values in swift programming language.

 

struct addition {

let adds: Int

subscript(i: Int) -> Int {

return adds + i

}

}

let insAdd = addition(adds: 45)

print("Subscript Value: \(insAdd[3])")

If you observe above example we created an instance for structure addition and sending initial value. We are querying structure instance by calling its subscript. 

 

When we run above program in swift playground we will get result like as shown below.

 

Subscript Value: 48

Following is the example of using subscript with getter and setter properties.

 

struct College {

var branches = ["CSE", "ECE", "IT"]

subscript(index: Int) -> String {

get {

return branches[index]

}

set (newValue) {

self.branches[index] = newValue

}

}

}

var clg = College()

clg[0] = "Civil"

clg[1] = "Mech"

print(clg[0])

print(clg[1])

If you observe above example we created an instance for structure College and sending a initial value. We are querying structure instance by calling its subscript. 

 

When we run above program in swift playground we will get result like as shown below.

 

Civil

Mech

This is how we can use subscripts with getter and setter properties in swift programming language.

Swift Subscripts Usage

Subscripts is depending upon programmer context how he will use it. Subscripts specially use as a shortcut to access the elements in a list, collection or sequence. 

 

Following is the example of implementing subscript to set and retrieve values stored in Dictionary object. We can set the value of dictionary by providing correct key name and assigning a value of dictionary value type to the subscript.

 

var studentsinbranch = ["CSE": 80, "ECE": 65, "IT": 44]

print(studentsinbranch)

studentsinbranch["IT"] = 67

studentsinbranch["EEE"] = 35

print(studentsinbranch)

If you observe above example we defined Dictionary object studentsinbranch with some initial key-value pairs. After that we used subscript to set or assign new values to dictionary object based on our requirements.

 

When we run above example in swift playground we will get result like as shown below

 

["CSE": 80, "ECE": 65, "IT": 44]

["CSE": 80, "EEE": 35, "ECE": 65, "IT": 67]

This is how we can use subscripts in swift programming language based on our requirements.

Swift Subscripts Options

In swift, subscripts can accept any number of input parameters and these input parameters can be of any data type and subscripts can also return any type. Subscripts cannot provide any default parameter values or use any in-out parameters.

 

In classes or structures we can define multiple subscripts based on our requirements and the process of defining multiple subscripts will call as a subscript overloading. The required subscript will be used based on the type of value that is declared within the subscript braces. 

 

Following is the example of defining a class with two dimensional values and subscript with multiple input parameters and used getter and setter properties to set values based on our requirements.

 

class Student {

var val1: String?

var val2: String?

subscript(row: Int, col: Int) -> String {

get {

if row == 0 {

if col == 0 {

return val1!

}

else {

return val2!

}

}

return val2!

}

set {

if row == 0 {

if col == 0 {

val1 = newValue

}

else {

val2 = newValue

}

}

}

}

}

var res = Student()

res[0,0] = "Suresh Dasari"

res[0,1] = "Rohini Alavala"

print(res[0,0])

print(res[0,1])

If you observe above example we defined a class to represent multi-dimensional values and created subscript to accept multiple input parameters and used getter and setter properties to set and retrieve values based on our requirements.

 

When we run above example in swift playground we will get result like as shown below

 

Suresh Dasari

Rohini Alavala

This is how we can use subscripts in collections to fetch elements based on our requirements in swift programming language. 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User