swift subscript scraps

// * * * * * Subscript * * * * * 

// similar to subscript to Array, Dictionary, Class/Struct/Enum can have too


// ???? what's the diff from function, I can replace subscript with func


struct IcanMultiply {

    var base:Int

    subscript(number:Int) ->Int{

        return number *base

    }

}


var someInt = IcanMultiply(base:3)

someInt[4]


struct Matrix {

    let rows,columns :Int

    var grid : [Double]

    init(row:Int,column:Int){

        rows = row

        columns = column

        grid = Array(repeating:0.0,count:row*column)

    }

    func isValidIndex(row:Int,column:Int) ->Bool{

        return row>=0&&row<rows&&column>=0&&column<columns

    }

    subscript(row:Int,column:Int) ->Double{

        get{

            assert(isValidIndex(row: row, column: column),"index out bound")

            return grid[row*columns+column]

        }

        set{

            assert(isValidIndex(row: row, column: column),"index out bound")

            grid[row*columns+column]=newValue

        }

    }

}


var someMatrix = Matrix(row:2, column: 2)

print(someMatrix.grid.count)

print(someMatrix.grid[0])

print(someMatrix[0,0])

//print(someMatrix[2,2])//assertion failed: index out bound:

someMatrix[0,0]=2.8

print(someMatrix[0,0])


when you using Subscript/Computed property, the getter and setter are used only when getting the value from the property or setting the value for the property, they will not be called in the same time. so there is no orderring problem.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值