Swift program to implement subscript overloading

Here, we are going to learn how to implement subscript overloading in Swift programming language?
Submitted by Nidhi, on July 13, 2021

Problem Solution:

Here, we will implement subscript overloading by creating two subscript functions with a different number of parameters.

Program/Source Code:

The source code to implement subscript overloading is given below. The given program is compiled and executed successfully.

// Swift program to implement subscript overloading

import Swift

struct Sample {
    var val1:Int
    var val2:Int

    subscript(row:Int) -> Int {
        return (row*val1)
    }

    subscript(row:Int, col:Int) -> Int {
        return (row*val1 + col*val2)
    }
}

var sam = Sample(val1:10,val2:20)

print(sam[1])
print(sam[2])
print(sam[3])
print(sam[4])
print(sam[1,1])
print(sam[2,2])
print(sam[3,3])
print(sam[4,4])

Output:

10
20
30
40
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 members val1, val2 and created two custom subscripts with the different number of 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!




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.