swift - 与方法相比,下标使用的额外优势是什么
问题描述
我在 Swift 中浏览下标,发现通过使用方法我们可以访问类、枚举或结构的成员元素。
那么下标提供了哪些额外的优势呢?
解决方案
Subscripts have three advantages over functions that I can think of:
Familiarity. Many Swift programmers are familiar with using
[]
to access array elements in other languages like Python, C, C++, and Java.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[]
. Comparearray[i]
toarray.at(i)
.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 })
推荐阅读
- laravel - mb_strpos() 期望参数 1 是字符串,在 Laravel 中查询 2 个表时给出的对象
- arrays - 如何从Matlab中的变量中获取单元格编号时在excel中读取一行?
- python - 如何从 sklearn.neighbors.KDTree 中检索节点?
- reactjs - 反应 scrollIntoView 未定义
- php - 如何将 php 数组作为 ajax 调用中的 post 参数传递给 url 中的 php 文件
- java - SCOPE_SINGLETON 和私有构造函数的区别
- git - 为什么合并后再次变基不是一个好习惯?
- python - 如何使用随机数作为 if 语句的输入?
- python-3.x - 如何使用python查看外面有多少光
- twilio - Twilio twiml 记录修剪选项不起作用