Swift Program to fetch elements from an array based on an index


In this article, we will learn how to write a swift program to fetch elements from an array based on an index.

Using array syntax

An array is used to store elements of same data type in an order whereas a set is used to store distinct elements of same data type without any definite order. In an array, every element has an index. The array index is start from 0 and goes up to N-1. Here N represent the total number of array elements. To retrieve elements from the array according to their index we can use subscript syntax.

Syntax

Array[Index]

Here array represent the name of the array and Index represent the position of the element in the array.

Example 1

Following Swift program to fetch elements from an array based on an index.

import Foundation
import Glibc

// Creating an array of integer type
let mArr = [733, 10, 11, 53, 24, 151, 45, 33]

print("Original array:", mArr)

// Getting fifth element of the array
let result1 = mArr[4]
print("Element at index 4:", result1)

// Getting second element of the array
let result2 = mArr[1]
print("Element at index 1:", result2)

Output

Original array: [733, 10, 11, 53, 24, 151, 45, 33]
Element at index 4: 24
Element at index 1: 10

Here in the above code, we have an array of integer type. Now using subscript syntax we find the element at index 4 = 24 and index 1 = 10.

Using Subscript Syntax

Using subscript syntax we can also use a range of indexes to get multiple elements from the array.

Syntax

Array[Index1…index2]

Here array represent the name of the array and Index1 represent the position of the first element and index2 represent the position of last element which we want to print from the given array.

Example 2

Following Swift program to fetch elements from an array based on an index.

import Foundation
import Glibc

// Creating an array of integer type
let mArr = [3, 45, 32, 98, 45, 98, 42, 12, 4, 6, 7, 8]

print("Original array:", mArr)

// Getting fifth and sixth elements of the array
let result1 = mArr[4...5]
print("Elements are:", result1)

// Getting all the elements from the array
let result2 = mArr[0..<mArr.count]
print("Elements are:", result2)

// Getting first four elements from the array
let result3 = mArr[0..<4]
print("Elements are:", result3)

Output

Original array: [3, 45, 32, 98, 45, 98, 42, 12, 4, 6, 7, 8]
Elements are: [45, 98]
Elements are: [3, 45, 32, 98, 45, 98, 42, 12, 4, 6, 7, 8]
Elements are: [3, 45, 32, 98]

Here in the above code, we have an array of integer type. Now we use range operator in the subscript syntax to retrieve multiple elements from the given array.

Conclusion

So this is how we can fetch elements from an array based on an index with the help of subscript syntax. Using subscript syntax you can also fetch data from multi-dimensional arrays.

Updated on: 17-Jan-2023

290 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements