感谢作者
https://www.jianshu.com/p/8c3112e355a7
// 下标,通过下标访问集合元素
// subscript
var matrix = Matrix.init(rows: 3, columns: 3)
print(matrix.description)
/*
输出的矩阵为:
|0.0|0.0|0.0|
|0.0|0.0|0.0|
|0.0|0.0|0.0|
*/
matrix[2,2] = 3.8 //!< 修改第2行第2列的元素为3.8
print(matrix.description)
/*
输出的矩阵为:
|0.0|0.0|0.0|
|0.0|0.0|0.0|
|0.0|0.0|3.8|
*/
matrix[1,1] = 6.0 //!< 修改第1行第1列的元素为6.0
print(matrix.description)
/*
输出的矩阵为:
|0.0|0.0|0.0|
|0.0|6.0|0.0|
|0.0|0.0|3.8|
*/
matrix[0,0,2.0] = 4.5
print(matrix.description)
/*
输出的矩阵为:
|9.0|0.0|0.0|
|0.0|6.0|0.0|
|0.0|0.0|3.8|
*/
// 类型下标
// static 或 class 修饰 subscript
// swift5.1 不能使用类型下标
struct Matrix {
var description: String {
var line = 0
var desStr = ""
for item in matrixArray.enumerated() {
if item.0 / columns == line {
desStr += "|" + String(item.1) + ""
} else {
line = item.0 / columns
desStr += "|"
//换行符
desStr += "\n" + "|" + String(item.1)
}
}
return "输出的矩阵为:"+"\n"+desStr + "|"
}
let rows : Int,columns : Int
var matrixArray : [Double]
init(rows:Int,columns : Int) {
self.rows = rows
self.columns = columns
matrixArray = Array.init(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
//! 获取和设置矩阵相应位置的元素
subscript(row:Int,column:Int)->Double {
get {
assert(indexIsValid(row: row, column: column), "行或者列的下标超出了矩阵的边界")
return matrixArray[row * columns + columns]
}
set {
assert(indexIsValid(row: row, column: column), "行或者列的下标超出了矩阵的边界")
matrixArray[row * columns + column] = newValue
}
}
//! 重载`Matrix`的下标:定义系数设置时累积
subscript(row:Int,column:Int,factor:Double)->Double{
get {
assert(indexIsValid(row: row, column: column), "行或者列的下标超出了矩阵的边界")
return matrixArray[row * columns + columns]
}
set {
assert(indexIsValid(row: row, column: column), "行或者列的下标超出了矩阵的边界")
matrixArray[row * columns + column] = newValue * factor
}
}
}
网友评论