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

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 is the first example that shows how to declare read-only subscripts:

//No getter/setters implicitly declared
subscript(index: Int) ->String {
  return names[index]
}

The following is the second example:

//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. So, Swift sets the subscript as read only and the code acts as if it was in a getter definition. In the second example, we specifically set the code in a getter definition. Both examples are valid read-only subscripts.