Read-only custom subscripts
We can also make the subscript read-only by either not declaring a setter method within the subscript or by not implicitly declaring a getter or setter method. The following code shows how to declare a read-only property by not declaring a getter or setter method:
//No getter/setters implicitly declared subscript(index: Int) ->String { return names[index] }
The following example shows how to declare a read-only property by only declaring a getter method:
//Declaring only a getter subscript(index: Int) ->String { get { return names[index] } }
In the first example, we do not define either a getter
or setter
method, therefore Swift sets the subscript as read-only and the code acts as if it was in a getter definition. In the second example, we specifically set the code in a getter definition. Both examples are valid read-only subscripts. One thing to note is write-only subscripts are not valid...