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

Get Mastering Swift 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.