Swift:subscript
本文转载自:http://blog.csdn.net/sinat_27706697/article/details/47122137 感谢作者:秋恨雪
通常情况下,我们在使用数组(Array)或字典(Dictionary)时会使用到下标。其实在Swift中,我们还可以给类、结构、枚举等自定义下标(subscript)。
一、基本使用
- struct TimesTable {
- let multiplier: Int
- subscript(index: Int) -> Int {
- return multiplier * index
- }
- }
我在TimesTable这个结构中自定义了一个subscript,并且这个subscript类似于方法,看上去它的类型为 Int -> Int。
然后在调用的时候,就可以使用"[index]"这样的形式取值。
- let threeTimesTable = TimesTable(multiplier: 3)
- println("six times three is \(threeTimesTable[7])")
二、使用subscript可以删除字典中的某个特定的key-value
- var numberOfLegs = ["spider":8,"ant":6,"cat":4]
- numberOfLegs["ant"] = nil
- println(numberOfLegs.count)
上面的numberOfLegs初始时候它有三对值,当进行numberOfLegs["ant"] = nil 操作后,相当于key为"ant"的key-value被删除了,所以打印的结果为2。
三、subscript中的索引参数不一定永远是一个Int类型的index,它也可以有多个参数。
例如,我们可以使用subscript将一维数组模拟成二维数组。
- struct Matrix {
- let rows: Int
- let cols: Int
- var grid: [Double]
- init(rows: Int, cols: Int) {
- self.rows = rows
- self.cols = cols
- self.grid = Array(count: rows * cols, repeatedValue: 0.0)
- }
- func indexIsValidForRow(row: Int, col: Int) -> Bool {
- return row >= 0 && row < rows && col >= 0 && col < cols;
- }
- subscript(row: Int, col: Int) -> Double {
- get {
- assert(indexIsValidForRow(row, col: col), "index out of range")
- return grid[row * cols + col]
- }
- set {
- assert(indexIsValidForRow(row, col: col), "index out of range")
- grid[row * cols + col] = newValue
- }
- }
- }
代码中的grid成员属性是一个含有rows * cols 个元素的一维数组。
然后定义一个subscript, 这里的下标有两个:row和col。然后根据具体的输入参数,从grid数组中取出对应的值。所以这里的下标只是模拟,看起来输入row和col,但实际还是从一维数组grid中取值。
调用效果如下:
- var matrix = Matrix(rows: 3, cols: 4)
- matrix[2, 1] = 3.4
- matrix[1, 2] = 5
- //
- var some2 = matrix[1, 2]
- println("some:\(some2)")
四、获取数组中指定索引位置的子数组,我们可以在Array的扩展中用subscript来实现。
- extension Array {
- subscript(input: [Int]) -> ArraySlice<T> {
- get {
- var array = ArraySlice<T>()
- for i in input {
- assert(i < self.count, "index out of range")
- array.append(self[i])
- }
- return array
- }
- set {
- // i表示数组input自己的索引,index表示数组self的索引
- for (i, index) in enumerate(input) {
- assert(index < self.count, "index out of range")
- self[index] = newValue[i]
- }
- }
- }
- }
代码中的input数组表示选取的Array中的某些下标。例如:
arr数组
- var arr = [1, 2, 3, 4, 5]
input数组
- var input = [0,2]
那么通过input中的值在arr数组中取得的子数组为 [1, 3]
subscript中的get方法就是根据input中的数组的下标值取得arr数组中对应下标的子数组。
subscript中的set方法就是根据input中的数组的下标值对arr数组中对应下标的内容重新赋值。
Swift:subscript的更多相关文章
- Swift 自定义Subscript
Swift可以方便给自定义类加下标,其中参数和返回值可以在类里定义为任意类型: subscript(parameters) -> ReturnType { get { //return some ...
- swift:高级运算符(位运算符、溢出运算符、优先级和结合性、运算符重载函数)
swift:高级运算符 http://www.cocoachina.com/ios/20140612/8794.html 除了基本操作符中所讲的运算符,Swift还有许多复杂的高级运算符,包括了C语和 ...
- iOS8 Core Image In Swift:视频实时滤镜
iOS8 Core Image In Swift:自己主动改善图像以及内置滤镜的使用 iOS8 Core Image In Swift:更复杂的滤镜 iOS8 Core Image In Swift: ...
- iOS8 Core Image In Swift:人脸检测以及马赛克
iOS8 Core Image In Swift:自动改善图像以及内置滤镜的使用 iOS8 Core Image In Swift:更复杂的滤镜 iOS8 Core Image In Swift:人脸 ...
- iOS8 Core Image In Swift:更复杂的滤镜
iOS8 Core Image In Swift:自动改善图像以及内置滤镜的使用 iOS8 Core Image In Swift:更复杂的滤镜 iOS8 Core Image In Swift:人脸 ...
- iOS8 Core Image In Swift:自动改善图像以及内置滤镜的使用
iOS8 Core Image In Swift:自动改善图像以及内置滤镜的使用 iOS8 Core Image In Swift:更复杂的滤镜 iOS8 Core Image In Swift:人脸 ...
- matlab错误:Subscript indices must either be real positive integers or logicals.
matlab错误:Subscript indices must either be real positive integers or logicals. 中文解释:下标索引必须是正整数类型或者逻辑类 ...
- Swift:UIKit中Demo(一)
关于Swift的基本概念及语法知识.我在前面的章节中已经介绍了非常多.这一节和下一节主要有针对性的解说Swift在实际UIKit开发中的使用场景及注意点.先来看看Demo的终于效果图. Demo分析: ...
- 杂项-语言-Swift:Swift
ylbtech-杂项-语言-Swift:Swift Swift,苹果于2014年WWDC(苹果开发者大会)发布的新开发语言,可与Objective-C*共同运行于Mac OS和iOS平台,用于搭建基于 ...
随机推荐
- Javascript--装饰器模式和观察者模式
装饰器模式 (function(){//装饰一棵树,装饰器模式通过对对象的属性进行改变来装饰对象.需要一个设置属性的方法 var tree={}; tree.decorate=function(){ ...
- oracle删除users表空间
1.users表空间一般情况下是默认的,需将别的空间设置成默认,再删除users表空间(oracle不允许删除默认空间的). 2.删除表空间的同时会报这样的错:ORA-22868错误.原因:推断应该存 ...
- Modelica学习
Annotation Choices for Suggested Redeclarations and Modifications Replaceable model sample(start,int ...
- c#自制视屏监控
项目需要开发一个监控程序,主要是监控其它电脑的操作情况. 先说下原理吧,首先我们列出做远程监控的基本步骤,远端电脑的ip,捕捉屏幕的方法,传输,接收并显示. 突然不知道怎么写下去了....... 程序 ...
- '++' needs l-value
碰到这样一段代码:char c[]= "abc";while(*c){printf("%c",*c);c++;} 错误定位到 c++ ; 这一行,提示: ' ...
- CentOS 7 安装php开发环境
安装服务 : yum install httpd httpd-devel service httpd start 启动 安装mariadb : yum -y install mariadb* ...
- Android开发环境
1: JDK 2: Eclipse 3: Android SDK 4: ADT
- mysql 存储过程 游标的使用
BEGINDECLARE id long;DECLARE Done INT DEFAULT 0;DECLARE userids CURSOR FOR SELECT userid from info_u ...
- JSP(include指令)页面
<%@ page language= "java" contentType="text/html;charset=UTF-8" %><html ...
- REMOVE ONCLICK DELAY ON WEBKIT FOR IPHONE
Developing on the webkit for iPhone I encountered a curious delay ononClick events. It seems that th ...