Swift program to create a custom subscript

Here, we are going to learn how to create a custom subscript in Swift programming language?
Submitted by Nidhi, on July 13, 2021

Problem Solution:

Here, we will create a custom subscript with structure by creating a function using the subscript keyword.

Program/Source Code:

The source code to create a custom subscript is given below. The given program is compiled and executed successfully.

// Swift program to create a simple subscript

import Swift

struct Sample {
    let value: Int
    subscript(index: Int) -> Int {
        return value * index
    }
}

let S = Sample(value: 5)

print(S[1])
print(S[2])
print(S[3])
print(S[4])
print(S[5])

Output:

5
10
15
20
25

...Program finished with exit code 0
Press ENTER to exit console.

Explanation:

In the above program, we imported a package Swift to use the print() function using the below statement,

import Swift

Here, we created a structure Sample that contains a member value. We defined a function with the subscript keyword. The subscript function returns an integer value based on the index passed to the function. Then we created a structure variable S with an initial value of 5. After that, we used the structure variable S with subscript operation "[]" and print the result on the console screen.

Swift Subscripts Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.