O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 look at how to use this subscript:

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

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required