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 look at the following example:
class MyNames {
private var names:[String] = ["Jon", "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...