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