Subscript values

In the preceding subscript examples, all of the subscripts accepted integers as the value for the subscript; however, we are not limited to integers. In the following example, we will use a string type as the value for the subscript. The subscript will also return a string type:

struct Hello {
  subscript (name: String) ->String {
    return "Hello \(name)"
  }
}

In this example, the subscript takes a string as the value within the subscript and returns a message, saying Hello. Let's see how to use this subscript:

var hello = Hello()
print(hello["Jon"])

This example will display the message, Hello Jon, to the console.

Get Swift: Developing iOS Applications 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.