Swift program to create a custom subscript with multiple options

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

Problem Solution:

Here, we will create a custom subscript with multiple options and return the value based on specified indices.

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.

// 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.

Swift Subscripts Programs »





Comments and Discussions!

Load comments ↻





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