下标

299 阅读1分钟
  1. 下标简单使用
struct TimesTable {
    var muti = 1
    
    subscript(index:Int) -> Int{
        return index * muti
    }
}

var timesTable = TimesTable(muti: 3)
print(timesTable[8])
  1. 下标用于访问数组字典
    1. dict[key]?= nil是为了赋值nil
    2. dict[key]= nil是为了删除key-value键值对
var dict = ["one": 1, "two": 2, "three": 3]
dict["four"] = 4
print(dict)

dict["three"] = nil
print(dict)
  1. 多个下标用法
    1. subscript支持子类重写
class Matrix {
    var rows: Int, cols:Int
    var grid: [Double]
    
    init(rows: Int, cols: Int) {
        self.rows = rows
        self.cols = cols
        grid = Array(repeating: 0.0, count: rows * cols)
    }
    
    func isInRange(row: Int, col: Int) -> Bool {
        return row >= 0 && row < self.rows && col >= 0 && col < self.cols
    }
    
    //subscript不存在类类型,支持子类重写
    subscript(row: Int, col: Int) -> Double {
        get {
            return grid[row * self.cols + col]
        }
        
        set {
            grid[row * self.cols + col] = newValue
        }
    }
    
}

class Test: Matrix{
   override subscript(row: Int, col: Int) -> Double {
        get {
            assert(isInRange(row: row, col: col),"越界")
            return grid[row * self.cols + col]
        }
        
        set {
            assert(isInRange(row: row, col: col),"越界")
            grid[row * self.cols + col] = newValue
        }
    }
}

var a = Test(rows: 3, cols: 3)
a[0,0] = 1
a[0,2] = 2
a[2,0] = 3
a[2,2] = 4

print("a[2,0] = \(a[2,0])")
//a[2,0] = 3.0
  1. swift5.1新增类类型下标
    1. 同样的static示例类型下标变成了类类型下标,并子类不能重写父类。
    2. 同样的class示例类型下标变成了类类型下标,并子类能重写父类。
enum Planet: Int {
    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
    class subscript(n: Int) -> Planet {
        return Planet(rawValue: n)!
    }
}
let mars = Planet[4]
print(mars)