本文转载自: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. Javascript--装饰器模式和观察者模式

    装饰器模式 (function(){//装饰一棵树,装饰器模式通过对对象的属性进行改变来装饰对象.需要一个设置属性的方法 var tree={}; tree.decorate=function(){ ...

  2. oracle删除users表空间

    1.users表空间一般情况下是默认的,需将别的空间设置成默认,再删除users表空间(oracle不允许删除默认空间的). 2.删除表空间的同时会报这样的错:ORA-22868错误.原因:推断应该存 ...

  3. Modelica学习

    Annotation Choices for Suggested Redeclarations and Modifications Replaceable model sample(start,int ...

  4. c#自制视屏监控

    项目需要开发一个监控程序,主要是监控其它电脑的操作情况. 先说下原理吧,首先我们列出做远程监控的基本步骤,远端电脑的ip,捕捉屏幕的方法,传输,接收并显示. 突然不知道怎么写下去了....... 程序 ...

  5. '++' needs l-value

    碰到这样一段代码:char c[]= "abc";while(*c){printf("%c",*c);c++;} 错误定位到   c++ ; 这一行,提示: ' ...

  6. CentOS 7 安装php开发环境

    安装服务 : yum install httpd httpd-devel  service httpd start 启动     安装mariadb : yum -y install mariadb* ...

  7. Android开发环境

    1: JDK 2: Eclipse 3: Android SDK 4: ADT

  8. mysql 存储过程 游标的使用

    BEGINDECLARE id long;DECLARE Done INT DEFAULT 0;DECLARE userids CURSOR FOR SELECT userid from info_u ...

  9. JSP(include指令)页面

    <%@ page language= "java" contentType="text/html;charset=UTF-8" %><html ...

  10. REMOVE ONCLICK DELAY ON WEBKIT FOR IPHONE

    Developing on the webkit for iPhone I encountered a curious delay ononClick events. It seems that th ...