下标(subscript)

2019-07-12  本文已影响0人  曹来东
class Point {
    var x = 0.0, y = 0.0
    subscript(index: Int) -> Double {
        
        set{
            if index == 0 {
                x = newValue
            }else if index == 1{
                y = newValue
            }
        }
        get {
            if index == 0 {
                return x
            } else if index == 1{
                return y
            }
            return 0
        }
    }
}
var p = Point()
p[0] = 11.1
p[1] = 22.2
print(p.x)//11.1
print(p.y)//22.2
print(p[0])//11.1
print(p[1])//22.2

下标的细节

class Point {
    var x = 0.0, y = 0.0
    subscript(index: Int) -> Double {
        get {
            if index == 0 {
                return x
            } else if index == 1{
                return y
            }
            return 0
        }
    }
}

class Point {
    var x = 0.0, y = 0.0
    subscript(index: Int) -> Double {
            if index == 0 {
                return x
            } else if index == 1{
                return y
            }
            return 0
    }
}
class Point {
    var x = 0.0, y = 0.0
    subscript(index i: Int) -> Double {
            if i == 0 {
                return x
            } else if i == 1{
                return y
            }
            return 0
    }
}
var p = Point()
print(p[index: 0])//11.1
print(p[index: 1])//22.2
class Sum {
    static subscript(v1: Int, v2: Int) -> Int{
        return v1 + v2
    }
}
print(Sum[10,20])//30

结构体和类作为下标返回值对比

class Point {
    var x = 0, y = 0
    
}
class PointManager {
    var point = Point()
    subscript(index: Int) -> Point{
        get { point }
    }
}
var pm = PointManager()
pm[0].x = 11
pm[0].y = 22
print(pm[0])
print(pm.point)
struct Point {
    var x = 0, y = 0
    
}
class PointManager {
    var point = Point()
    subscript(index: Int) -> Point{
        set{ point = newValue }
        get { point }
    }
}
var pm = PointManager()
pm[0].x = 11
pm[0].y = 22
print(pm[0])
print(pm.point)

接受多个参数的下标

class Grid {
    var data = [
        [0,1,2],
        [3,4,5],
        [6,7,8]
    ]
    subscript(row: Int, column: Int) -> Int{
        set {
            guard row >= 0 && row < 3 && column >= 0 && column < 3 else{
                return
            }
            data[row][column]
        }
        get {
            guard row >= 0 %% row < 3 && column >= 0 && column < 3 else{
                return
            }
            return data[row][column]
        }
    }
}

var grid = Grid()
grid[0,1] = 77
grid[1,2] = 77
grid[2,0] = 77
print(grid.data)

上一篇下一篇

猜你喜欢

热点阅读