Swift代码库之数组作为参数传输保证数据修改有效

it2025-09-04  55

Swift 函数传递参数过程中会对参数进行复制,因此如果我们在函数里修改了array或者dictionary内容,返回主函数就会发现内容并未修改。如何解决呢?

使用inout关键词解决

调用时使用&

findeLevel3Add(bushou: bushou,wordList: &wordList,sIndex: sIndex )

函数定义时给需要参数加上inout关键词即可

func findeLevel3Add(bushou:String,wordList:inout [Any],sIndex:Int) { var oldItem=wordList[sIndex] as! Dictionary<String,Any> var children=oldItem["children"] as? [Any] if children != nil{ for cItem in children!{ var cOneItem = cItem as! [String:Any] let cName = cOneItem["name"] as! String if cName == bushou{ //如果已经存在则跳出 return } } //运行到此处,证明没有,则添加 let sItem=["name":bushou,"id":bushou] children!.append(sItem) oldItem["children"]!=children! wordList.remove(at: sIndex) wordList.insert(oldItem, at: sIndex) return } children = [Dictionary<String,Any>]() let sItem=["name":bushou,"id":bushou] children!.append(sItem) oldItem["children"]!=children! wordList.remove(at: sIndex) wordList.insert(oldItem, at: sIndex) }

往期精彩

请点击,免费订阅《学Swift挣美元》专栏 赚钱App研究之生成代码app 赚钱App研究之格式转换类app
最新回复(0)