Swift program to create a subscript with set/get property

Here, we are going to learn how to create a subscript with set/get property in Swift programming language?
Submitted by Nidhi, on July 13, 2021

Problem Solution:

Here, we will create a custom subscript with set/get the property to set and get the value of a structure member.

Program/Source Code:

The source code to create a subscript with the set/get property is given below. The given program is compiled and executed successfully.

// Swift program to create a 
// subscript with set/get property

import Swift

struct Colors {
    private var colors = ["Red", "Green", "Blue", "White","Black"]
    subscript(index: Int) -> String {
        get {
            return colors[index]
        }
        set(newValue) {
            self.colors[index] = newValue
        }
    }
}

var Col = Colors()

Col[3] = "Yellow"

print(Col[0])
print(Col[1])
print(Col[2])
print(Col[3])
print(Col[4])

Output:

Red
Green
Blue
Yellow
Black

...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 Colors that contains an array of strings colors.  In the Colors structure, we defined a property using the subscript keyword to set and get the value of the colors array based on an index. Then we created a structure variable Col and set the value "Yellow" at index 3. After that, we printed the values of the colors array based on the index.

Swift Subscripts Programs »






Comments and Discussions!

Load comments ↻






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