Swift Subscripts

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:-

Syntax for read only:-

Example:-

Output:-

swift_subscript_readonly

Example:-

Output:-

swift_subscript

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:-

Output:-

swift_subscript_options

In this tutorial we have learn about the Swift Subscripts and its application with practical example. I hope you will like this tutorial.