Swift Program To Create A Subscript With Set/Get Property

You are currently viewing Swift Program To Create A Subscript With Set/Get Property

Swift Program To Create A Subscript With Set/Get Property

// 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.

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply