在Swift中不允許修改方法函數(shù)中的參數(shù)值,因為方法中參數(shù)傳遞的是值而不是地址,參數(shù)被修改時編譯器會認(rèn)為此參數(shù)為常量類型,并且提示'Cannot assign to value: 'xxx' is a 'let' constant'的錯誤。
看下面代碼:
func verifyInout() -> Void {
let datas: [Any] = [1,2,3,4,5,6]
print("datas",datas)
handleData(datas: datas)
print("\(#function)", datas)
}
func handleData(datas:[Any]) -> Void {
datas = [7,8,9,0]
print("\(#function)",datas)
}
此時會報錯誤

那如何實現(xiàn)方法/函數(shù)參數(shù)可以被修改呢?
解決方法:使用inout將方法/函數(shù)參數(shù)定義為輸入輸出形式參數(shù);
在形式參數(shù)定義開始的時候在前邊添加一個 inout關(guān)鍵字可以定義一個輸入輸出形式參數(shù)。輸入輸出形式參數(shù)有一個能輸入給函數(shù)的值,函數(shù)能對其進(jìn)行修改,還能輸出到函數(shù)外邊替換原來的值.
將上面的代碼進(jìn)行修改就可以了
func verifyInout() -> Void {
var datas: [Any] = [1,2,3,4,5,6]
print("datas",datas)
handleData(datas: &datas)
print("\(#function)", datas)
}
func handleData(datas: inout [Any]) -> Void {
datas = [7,8,9,0]
datas.insert(contentsOf: [11,12], at: 2)
print("\(#function)",datas)
}
調(diào)用時使用&取地址,想方法中傳入地址
handleData(datas: &datas)
注意:只能把變量作為輸入輸出形式參數(shù)的實際參數(shù)。你不能用常量或者字面量作為實際參數(shù),因為常量和字面量不能修
查看對象內(nèi)存結(jié)構(gòu)
fr v -R datas 和 fr v -R &datas
