The source code to create a custom subscript with multiple options is given below. The given program is compiled and executed successfully.
// Swift program to create a custom subscript
// with multiple options
import Swift
struct Sample {
var val1:Int
var val2:Int
subscript(row:Int, col:Int) -> Int {
return (row*val1 + col*val2)
}
}
var sam = Sample(val1:10,val2:20)
print(sam[1,1])
print(sam[2,2])
print(sam[3,3])
print(sam[4,4])
Output:
30
60
90
120
...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 two data member val1, val2 and a custom subscript that accept two arguments and return an integer value. Then we created a structure variable and initialized the value of val1 and val2. After that, we used the subscript operator "[]" and get the values based on the passed index and printed them on the console screen.
Program/Source Code:
The source code to create a custom subscript with multiple options 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 two data member val1, val2 and a custom subscript that accept two arguments and return an integer value. Then we created a structure variable and initialized the value of val1 and val2. After that, we used the subscript operator "[]" and get the values based on the passed index and printed them on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer