Search code examples
swiftmethodssubscript

What is additional advantage of subscript use over method


I was going through subscripts in Swift and found that with use of methods we can access the member elements of class, enum or struct.

Then what additional advantage does subscript provide?


Solution

  • Subscripts have three advantages over functions that I can think of:

    1. Familiarity. Many Swift programmers are familiar with using [] to access array elements in other languages like Python, C, C++, and Java.

    2. Terseness. If you want to access a collection element using a function, the function needs a name. Even a short name like at (which Smalltalk uses) requires more characters than []. Compare array[i] to array.at(i).

    3. Flexibility. A subscript operator can allow both reading and writing. You can even use a subscript operator on the left side of a mutating binary operator, like this:

      array[i] += 1
      

      Without the subscript operator, you'd need to explicitly write two separate function calls, like this:

      array.at(i, put: array.at(i) + 1)
      

      Or maybe use a function that takes a mutation closure, like this:

      array.at(i, update: { $0 + 1 })