Read now

Subscripts In Swift

Subscripts are typically used as a shortcut for accessing the collection, sequence, and a list in Classes, Structures, and Enum without using a method. It used to store and retrieve the values without the use of separate methods. To access elements via this write one or more values between square brackets after the instance name. It can take any number of input parameters, and these input parameters can be of any type.

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:

Consider the Matrix structure, which represents a two-dimensional matrix of  Double values. It takes two integer parameters (rows and columns) :

Matrix is initialized by two parameters (rows and columns)  and creates an array of size rows * columns to store double value. Initially, we store value for each index in the array is 0.

So, let’s create the Matrix instance by adding the row and column in the parameter of its initializer.

Now, the grid array form as:

So, set the value of the Matrix by adding the row and column.

So, the grid array changed as:

 

The Matrix subscript’s getter and setter and both have checked the assertion that the subscript’s rows and columns values are valid. Because in some cases it can be out of the index.

 

Conclusion

So if you have any comments, questions, or recommendations, feel free to post them in the comment section below!

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close