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

Get Mastering Swift 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.