swift3 下标subscript

下标是方法的一种,是访问集合、列表或者序列中的元素的快捷方式。

定义形式:一个名为subscript的计算属性;可以忽略set(只读)
用法实例名[索引]
作用:可以访问或设置其中元素。

1.常见的用法:字典、数组等

var 数组1 = [1,2,3,55,6,-9,0]
数组1[3]  //55

let 字典1 = ["a":1,"b": 2,"c":3]
字典1["b"]    //2

2.通过下标简化调用方法调用

//pow(x,y) //其作用是计算x的y次方
struct 圆 {
    //一般方法
    func 面积(半径:Double) ->Double {
        return M_PI * pow(半径,2)
    }
    //使用下标subscript简化调用方法
    subscript(半径:Double) ->Double {
        return M_PI * pow(半径,2)
    }
}

let 圆1 = 圆()
圆1.面积(半径: 3.3)  //34.21194399759284
//使用下标1[3.3] //34.21194399759284

3.多维下标

get:用于获取属性的值
set:用于设置属性的值
assert(a,b) //第一个参数为判断条件(BOOL),第二个参数为条件”不满足”时的打印信息(String)。

3.1 下标可读可写

struct Matrix {
    var rows,cols : Int
    var grid: [Int]

    init(rows: Int,cols: Int) {
        self.cols = cols
        self.rows = rows

        grid = Array(repeating: 0,count: rows * cols)
    }

    func indexIsValid(row:Int,col:Int) -> Bool {
        return row >= 0 && row < rows && col >= 0 && col < cols
    }

    subscript(row:Int,col:Int) ->Int {
        get {
            assert(indexIsValid(row: row,col: col),"数组索引越界")
            return grid[col + (row * cols)]
        }
        set {
            assert(indexIsValid(row: row,"数组索引越界")

            grid[col + (row * cols)] = newValue
        }
    }
}
//写
var matrix1 = Matrix(rows: 3,cols: 3)
matrix1[0,0] = 7
matrix1[0,1] = 5
matrix1[0,2] = -9
matrix1[1,0] = 8
matrix1[1,1] = 9
matrix1[1,2] = 99
matrix1[2,0] = -8
matrix1[2,1] = -9
matrix1[2,2] = -99

matrix1.grid    //[7,5,-9,8,9,99,-8,-99]
//读
matrix1[2,2]    //-99

3.2 下标只读

class SectionAndRow {
    var array:Array<Array<Int>> = [ [1,2],[3,4],[5,6],[7,8]
    ]

    subscript(section:Int,row:Int)->Int{

        //忽略get块创建只写属性,忽略set块创建只读属性
        get{
            print(array.count)
            print(array[section].count)
            assert(section >= 0 && section < array.count && row >= 0 && row < array[section].count,"数组索引越界")
            let temp = array[section]
            return temp[row]
        }
    }
}
var data = SectionAndRow()
//通过二维下标取值
data[3,1]    //8

参考自SwiftV课堂视频源码

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...