inout用来指针传递
指针传递把参数本身引用(内存地址)传递过去,在调用的过程会影响原始数据。
在Swift众多数据类型中,只有class是指针传递,其余的如Int,Float,Bool,Character,Array,Set,enum,struct全都是值传递.
让值传递以指针方式传递
有时候我们需要通过一个函数改变函数外面变量的值(将一个值类型参数以引用方式传递)
var stepSize=1
func increment(_ number: inout Int){
number += stepSize
}
var stepSize2=1
increment(&stepSize2)
print(stepSize2)
结果2
但是如果同时操作stepSize 就会出现问题
var stepSize=1
func increment(_ number: inout Int){
number += stepSize
}
var stepSize2=1
increment(&stepSize)
print(stepSize)
inout 是去写数据 += 得时候是读数据
所以就出现这个问题了
当同时写一个对象数据得时候也会出现这个问题