Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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()
println(hello["Jon"])

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