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.
Program/Source Code:
The source code to create a custom subscript is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we imported a package Swift to use the print() function using the below statement,
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