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

When not to use a custom subscript


As we have seen in this chapter, creating custom subscripts can really enhance our code; however, we should avoid overusing them or using them in a way that is not consistent with standard subscript usage. The way to avoid overusing subscripts is to examine how subscripts are used in Swift's standard libraries. Let's take a look at the following example:

class MyNames {
  private var names:[String] = ["Jon", "Kim", "Kailey", "Kara"]
  var number: Int {
    get {
      return names.count
    }
  }
  subscript(add name: String) -> String {
    names.append(name)
    return name
  }
  subscript(index: Int) -> String {
    get {
      return names[index]
    }
    set {
      names[index] = newValue
    }
  }
}

In the preceding example, within the MyNames class, we define an array of names that are used within our application. As an example, let's say that within our application we display this list of names and we allow users to add names to it. Within...