Q:

Swift program to create a custom subscript

belongs to collection: Swift Subscripts Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Swift program to create a subscript with set/get p... >>