- Swift Tutorial
- Swift - Home
- Swift - Overview
- Swift - Environment
- Swift - Basic Syntax
- Swift - Variables
- Swift - Constants
- Swift - Literals
- Swift - Comments
- Swift Operators
- Swift - Operators
- Swift - Arithmetic Operators
- Swift - Comparison Operators
- Swift - Logical Operators
- Swift - Assignment Operators
- Swift - Bitwise Operators
- Swift - Misc Operators
- Swift Advanced Operators
- Swift - Operator Overloading
- Swift - Arithmetic Overflow Operators
- Swift - Identity Operators
- Swift - Range Operators
- Swift Data Types
- Swift - Data Types
- Swift - Integers
- Swift - Floating-Point Numbers
- Swift - Double
- Swift - Boolean
- Swift - Strings
- Swift - Characters
- Swift - Type Aliases
- Swift - Optionals
- Swift - Tuples
- Swift - Assertions and Precondition
- Swift Control Flow
- Swift - Decision Making
- Swift - if statement
- Swift - if...else if...else Statement
- Swift - if-else Statement
- Swift - nested if statements
- Swift - switch statement
- Swift - Loops
- Swift - for in loop
- Swift - While loop
- Swift - repeat...while loop
- Swift - continue statement
- Swift - break statement
- Swift - fall through statement
- Swift Collections
- Swift - Arrays
- Swift - Sets
- Swift - Dictionaries
- Swift Functions
- Swift - Functions
- Swift - Nested Functions
- Swift - Function Overloading
- Swift - Recursion
- Swift - Higher-Order Functions
- Swift Closures
- Swift - Closures
- Swift-Escaping and Non-escaping closure
- Swift - Auto Closures
- Swift OOps
- Swift - Enumerations
- Swift - Structures
- Swift - Classes
- Swift - Properties
- Swift - Methods
- Swift - Subscripts
- Swift - Inheritance
- Swift-Overriding
- Swift - Initialization
- Swift - Deinitialization
- Swift Advanced
- Swift - ARC Overview
- Swift - Optional Chaining
- Swift - Error handling
- Swift - Concurrency
- Swift - Type Casting
- Swift - Nested Types
- Swift - Extensions
- Swift - Protocols
- Swift - Generics
- Swift - Access Control
- Swift - Function vs Method
- Swift - SwiftyJSON
- Swift - Singleton class
- Swift Random Numbers
- Swift Opaque and Boxed Type
- Swift Useful Resources
- Swift - Compile Online
- Swift - Quick Guide
- Swift - Useful Resources
- Swift - Discussion
Swift - Subscripts
Subscript is a special feature provided by Swift to access the element of a collection, sequence and list. It is the most convenient way to get or set values in the collection. We can also get or set values according to their index using subscripts. Even classes, structure and enumeration can define subscripts.
A single type can have multiple subscripts. We can use the appropriate subscript to overload according to the type of index value passed to the subscript. We can define a subscript that can take single as well as multiple parameters according to our requirements.
Subscript Declaration
We can define subscript using the subscript keyword and can take one or more input parameters and return type. It can be read-write or read-only. It allows us to perform queries on the instance by writing one or more values in square brackets followed by the instance name.
Syntax
Following is the syntax of the subscript −
subscript(index: Int) -> Int { get { // Retrieve the value at the specified index } set(newValue) { // Set the value at the specified index } }
Following is the syntax of read-only subscript −
subscript(index: Int) -> Int { // Return subscript value here }
Example
Swift program to retrieve values using subscript syntax.
// Defining structure struct subexample { let decrementer: Int // Declaring subscript subscript(index: Int) -> Int { return decrementer / index } } // Creating instance of the structure let division = subexample(decrementer: 100) // Retrieving values using subscript syntax print("The number is divisible by \(division[9]) times") print("The number is divisible by \(division[2]) times") print("The number is divisible by \(division[3]) times") print("The number is divisible by \(division[5]) times") print("The number is divisible by \(division[7]) times")
Output
It will produce the following output −
The number is divisible by 11 times The number is divisible by 50 times The number is divisible by 33 times The number is divisible by 20 times The number is divisible by 14 times
Example
Swift program to access values using subscript syntax.
// Defining class class daysofaweek { private var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] // Declaring subscript subscript(index: Int) -> String { // Retrieve the value at the specified index get { return days[index] } // Set the value at the specified index set(newValue) { self.days[index] = newValue } } } // Creating instance of class var p = daysofaweek() // Accessing elements using subscript print(p[0]) print(p[1]) print(p[2]) print(p[3])
Output
It will produce the following output −
Sunday Monday Tuesday Wednesday
Options in Subscript
Subscripts can take single or multiple input parameters of any data type and it can also return a value of any data type. These parameters can have default values. Subscripts can use variadic parameters but they cannot use in-out parameters.
Defining multiple subscripts is termed as 'subscript overloading' where a class or structure can provide multiple subscript definitions as required. These multiple subscripts are inferred based on the types of values that are declared within the subscript braces.
Example
Swift program to access values using subscript syntax.
// Defining structure struct Matrix { let rows: Int, columns: Int var print: [Double] // Initializer to create a matrix init(rows: Int, columns: Int) { self.rows = rows self.columns = columns // Initializing the matrix with an array print = Array(repeating: 0.0, count: rows * columns) } // Subscript for accessing and modifying elements in the matrix subscript(row: Int, column: Int) -> Double { get { return print[(row * columns) + column] } set { print[(row * columns) + column] = newValue } } } // Creating an instance var mat = Matrix(rows: 3, columns: 3) // Modifying elements in the matrix using subscript notation mat[0, 0] = 1.0 mat[0, 1] = 2.0 mat[1, 0] = 3.0 mat[1, 1] = 5.0 // Accessing and printing elements from the matrix using subscript notation print("\(mat[0, 0])") print("\(mat[0, 1])") print("\(mat[1, 0])") print("\(mat[1, 1])")
Output
It will produce the following output −
1.0 2.0 3.0 5.0