Swift - 使用set,get确保索引加减在正常的范围内
通过类的计算属性set和get,我们可以对索引的加减进行保护。下面是一个样例,索引index初始值是0,有效范围是0~2。不管是index++还是index--,索引都是一直在这个范围能循环遍历。
class Test {
var _index = 0
var index:Int {
get{
return _index
}
set{
_index = newValue
if _index < 0 {
_index += 3
}else if _index > 2 {
_index -=3
}
}
}
func onNext(){
index++
}
func onPre(){
index--
}
}
