Swift program to create a custom subscript

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

Problem Solution:

Here, we will create a custom subscript with structure by creating a function using the subscript keyword.

Program/Source Code:

The source code to create a custom subscript is given below. The given program is compiled and executed successfully.

// Swift program to create a simple subscript

import Swift

struct Sample {
    let value: Int
    subscript(index: Int) -> Int {
        return value * index

let S = Sample(value: 5)




...Program finished with exit code 0
Press ENTER to exit console.


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 a member value. We defined a function with the subscript keyword. The subscript function returns an integer value based on the index passed to the function. Then we created a structure variable S with an initial value of 5. After that, we used the structure variable S with subscript operation "[]" and print the result on the console screen.

Swift Subscripts Programs »


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.