ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.