本文转载自:http://blog.csdn.net/sinat_27706697/article/details/47122137 感谢作者:秋恨雪

通常情况下,我们在使用数组(Array)或字典(Dictionary)时会使用到下标。其实在Swift中,我们还可以给类、结构、枚举等自定义下标(subscript)。

一、基本使用

  1. struct TimesTable {
  2. let multiplier: Int
  3. subscript(index: Int) -> Int {
  4. return multiplier * index
  5. }
  6. }

我在TimesTable这个结构中自定义了一个subscript,并且这个subscript类似于方法,看上去它的类型为 Int -> Int。

然后在调用的时候,就可以使用"[index]"这样的形式取值。

  1. let threeTimesTable = TimesTable(multiplier: 3)
  2. println("six times three is \(threeTimesTable[7])")

二、使用subscript可以删除字典中的某个特定的key-value

  1. var numberOfLegs = ["spider":8,"ant":6,"cat":4]
  2. numberOfLegs["ant"] = nil
  3. println(numberOfLegs.count)

上面的numberOfLegs初始时候它有三对值,当进行numberOfLegs["ant"] = nil 操作后,相当于key为"ant"的key-value被删除了,所以打印的结果为2。

三、subscript中的索引参数不一定永远是一个Int类型的index,它也可以有多个参数。

例如,我们可以使用subscript将一维数组模拟成二维数组。

  1. struct Matrix {
  2. let rows: Int
  3. let cols: Int
  4. var grid: [Double]
  5. init(rows: Int, cols: Int) {
  6. self.rows = rows
  7. self.cols = cols
  8. self.grid = Array(count: rows * cols, repeatedValue: 0.0)
  9. }
  10. func indexIsValidForRow(row: Int, col: Int) -> Bool {
  11. return row >= 0 && row < rows && col >= 0 && col < cols;
  12. }
  13. subscript(row: Int, col: Int) -> Double {
  14. get {
  15. assert(indexIsValidForRow(row, col: col), "index out of range")
  16. return grid[row * cols + col]
  17. }
  18. set {
  19. assert(indexIsValidForRow(row, col: col), "index out of range")
  20. grid[row * cols + col] = newValue
  21. }
  22. }
  23. }

代码中的grid成员属性是一个含有rows * cols 个元素的一维数组。

然后定义一个subscript, 这里的下标有两个:row和col。然后根据具体的输入参数,从grid数组中取出对应的值。所以这里的下标只是模拟,看起来输入row和col,但实际还是从一维数组grid中取值。

调用效果如下:

  1. var matrix = Matrix(rows: 3, cols: 4)
  2. matrix[2, 1] = 3.4
  3. matrix[1, 2] = 5
  4. //
  5. var some2 = matrix[1, 2]
  6. println("some:\(some2)")

四、获取数组中指定索引位置的子数组,我们可以在Array的扩展中用subscript来实现。

  1. extension Array {
  2. subscript(input: [Int]) -> ArraySlice<T> {
  3. get {
  4. var array = ArraySlice<T>()
  5. for i in input {
  6. assert(i < self.count, "index out of range")
  7. array.append(self[i])
  8. }
  9. return array
  10. }
  11. set {
  12. // i表示数组input自己的索引,index表示数组self的索引
  13. for (i, index) in enumerate(input) {
  14. assert(index < self.count, "index out of range")
  15. self[index] = newValue[i]
  16. }
  17. }
  18. }
  19. }

代码中的input数组表示选取的Array中的某些下标。例如:

arr数组

  1. var arr = [1, 2, 3, 4, 5]

input数组

  1. var input = [0,2]

那么通过input中的值在arr数组中取得的子数组为 [1, 3]

subscript中的get方法就是根据input中的数组的下标值取得arr数组中对应下标的子数组。

subscript中的set方法就是根据input中的数组的下标值对arr数组中对应下标的内容重新赋值。

Swift:subscript的更多相关文章

  1. Swift 自定义Subscript

    Swift可以方便给自定义类加下标,其中参数和返回值可以在类里定义为任意类型: subscript(parameters) -> ReturnType { get { //return some ...

  2. swift:高级运算符(位运算符、溢出运算符、优先级和结合性、运算符重载函数)

    swift:高级运算符 http://www.cocoachina.com/ios/20140612/8794.html 除了基本操作符中所讲的运算符,Swift还有许多复杂的高级运算符,包括了C语和 ...

  3. iOS8 Core Image In Swift:视频实时滤镜

    iOS8 Core Image In Swift:自己主动改善图像以及内置滤镜的使用 iOS8 Core Image In Swift:更复杂的滤镜 iOS8 Core Image In Swift: ...

  4. iOS8 Core Image In Swift:人脸检测以及马赛克

    iOS8 Core Image In Swift:自动改善图像以及内置滤镜的使用 iOS8 Core Image In Swift:更复杂的滤镜 iOS8 Core Image In Swift:人脸 ...

  5. iOS8 Core Image In Swift:更复杂的滤镜

    iOS8 Core Image In Swift:自动改善图像以及内置滤镜的使用 iOS8 Core Image In Swift:更复杂的滤镜 iOS8 Core Image In Swift:人脸 ...

  6. iOS8 Core Image In Swift:自动改善图像以及内置滤镜的使用

    iOS8 Core Image In Swift:自动改善图像以及内置滤镜的使用 iOS8 Core Image In Swift:更复杂的滤镜 iOS8 Core Image In Swift:人脸 ...

  7. matlab错误:Subscript indices must either be real positive integers or logicals.

    matlab错误:Subscript indices must either be real positive integers or logicals. 中文解释:下标索引必须是正整数类型或者逻辑类 ...

  8. Swift:UIKit中Demo(一)

    关于Swift的基本概念及语法知识.我在前面的章节中已经介绍了非常多.这一节和下一节主要有针对性的解说Swift在实际UIKit开发中的使用场景及注意点.先来看看Demo的终于效果图. Demo分析: ...

  9. 杂项-语言-Swift:Swift

    ylbtech-杂项-语言-Swift:Swift Swift,苹果于2014年WWDC(苹果开发者大会)发布的新开发语言,可与Objective-C*共同运行于Mac OS和iOS平台,用于搭建基于 ...

随机推荐

  1. c++ 11 sleep()

    #include<chrono>#include<thread> std::this_thread::sleep_for(std::chrono::milliseconds(1 ...

  2. PHP form 表单传参明细研究

    GET表单: 复制代码代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "h ...

  3. 又是一天String

    (1) Length of Last Word 解题思路:使用length记录最后一个单词的长度.从最后一个字符开始,如果是空字符,length不变.如果不是空字符,length++,直到再次遇到空字 ...

  4. cordova常用资料源

    cordova的中文资料https://github.com/CordovaCn/CordovaCn 官方文档: http://cordova.apache.org/docs/en/latest/ E ...

  5. [字符编码]Invalid byte 1 of 1-byte UTF-8 sequence终极解决方案

    今天在eclipse中编写pom.xml文件时,注释中的中文被eclipse识别到错误:Invalid byte 1 of 1-byte UTF-8 sequence,曾多次遇到该问题,问题的根源是: ...

  6. modelsim 中 WAVE窗口中能不能只显示变量名,而不显示路径

    可以的,在wave窗口左下角有一个黑色的logo,你点击它就可以省电路径,只显示port名称,再点击就切换回来了,如图红色圈圈标记的logo,你可以试试!

  7. mysql从零开始

    常用的数据库有哪些? oralce,sqlserver,mysql,db2 有钱就用oracle吧 oracle和mysql的区别:https://zhidao.baidu.com/question/ ...

  8. Android停止运行问题1_layout布局xml问题

    好好的写了300多行布局文件代码,写完之后运行结果,停止运行了.我当时就奇怪,xml有错误应该会提示啊,我就一个一个的缩小错误的代码范围,先直接换成一个简单的TextView ,运行一下没有错误.再慢 ...

  9. deep learning on object detection

    回归工作一周,忙的头晕,看了两三篇文章,主要在写各种文档和走各种办事流程了-- 这次来写写object detection最近看的三篇文章吧.都不是最近的文章,但是是今年的文章,我也想借此让自己赶快熟 ...

  10. HTML5离线篇收藏--- cache manifest

    自从翻译了<解读 HTML5:建议.技巧和技术>,就一直没有时间去看 HTML5 相关的东西.上周一次偶然的工作间隙折腾了下 Cache Manifest .当时直接拿博客当测试环境,虽然 ...