首页 > 解决方案 > 与方法相比,下标使用的额外优势是什么

问题描述

我在 Swift 中浏览下标,发现通过使用方法我们可以访问类、枚举或结构的成员元素。

那么下标提供了哪些额外的优势呢?

标签: swiftmethodssubscript

解决方案


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 })
    

推荐阅读