The source code to create a subscript with read-only property is given below. The given program is compiled and executed successfully.
// Swift program to create a subscript
// with the read-only property
import Swift
struct Colors {
private var colors = ["Red", "Green", "Blue", "White","Black"]
subscript(index: Int) -> String {
get {
return colors[index]
}
}
}
var Col = Colors()
// Col[3] = "Yellow" //this statement will generate error.
print(Col[0])
print(Col[1])
print(Col[2])
print(Col[3])
print(Col[4])
Output:
Red
Green
Blue
White
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 read-only property using the subscript keyword to get the value of the colors array based on the index. Then we created a structure variable Col. After that, we printed the values of the colors array based on the index.
Program/Source Code:
The source code to create a subscript with read-only property is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we imported a package Swift to use the print() function using the below statement,
Here, we created a structure Colors that contains an array of strings colors. In the Colors structure, we defined a read-only property using the subscript keyword to get the value of the colors array based on the index. Then we created a structure variable Col. After that, we printed the values of the colors array based on the index.
need an explanation for this answer? contact us directly to get an explanation for this answer