Q:

Swift program to create a custom subscript with multiple options

belongs to collection: Swift Subscripts Programs

0

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

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 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 val1val2 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

total answers (1)

Swift program to overload init() method... >>
<< Swift program to create a subscript with the read-...