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 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 is used within our application. As an example, let's say that within our application we display this list of names and allow users to add names to it. Within the MyNames class, we then define the following subscript, which allows us to append a new name to the array:

subscript(add name: String) -> String { 
  names.append(name) 
  return name 
} 

This would be a poor use of subscripts because its usage is not consistent with how subscripts are used within the Swift language itself. This might cause confusion when the class is used. It would be more appropriate to rewrite this subscript as a function, such as the following:

func append(name: String) { 
  names.append(name) 
} 
Remember, when you are using custom subscripts, make sure that you are using them appropriately.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset