swift3 下标subscript
发布时间:2020-12-14 06:21:16 所属栏目:百科 来源:网络整理
导读:下标是方法的一种,是访问集合、列表或者序列中的元素的快捷方式。 定义形式: 一个名为subscript的计算属性;可以忽略set(只读) 用法: 实例名[索引] 作用: 可以访问或设置其中元素。 1.常见的用法:字典、数组等 var 数组 1 = [ 1 , 2 , 3 , 55 , 6 ,-
下标是方法的一种,是访问集合、列表或者序列中的元素的快捷方式。
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.多维下标
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课堂视频源码 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容