gpt4 book ai didi

arrays - 在swift中找到后修改数组元素不起作用

转载 作者:行者123 更新时间:2023-11-30 12:00:19 24 4
gpt4 key购买 nike

我写了一个这样的模型作为练习:

struct Store {
var name : String
var bills : Array<Bill>
var category : Category?
}

struct Bill {
var date : String
var amount : Float
}

struct Category {
var name : String
var tags : Array<String>
}

当我搜索商店是否已存在并向其添加账单而不是创建新商店时,我的代码不起作用。它的行为就像搜索结果是数组元素的副本一样。我想要一个引用。

var stores : Array <Store> = Array()
for billStatment in billStatements! {
let billParts = billStatment.split(separator: ",")
if billParts.count > 0 {
let bill : Bill = Bill(date:String(billParts[0]), amount: Float(billParts[2])!)
var store : Store = Store(name:String(billParts[1]), bills: [bill], category: nil)


if var alreadyAddedStore = stores.first(where: {$0.name == String(billParts[1])}) {
alreadyAddedStore.bills.append(bill)
print("yeah found it \(alreadyAddedStore)") // the debugger breaks here so I know the "first" method is working. If I print alreadyAddedStore here I have one more element, that's fine.
} else {
stores.append(store)
}

}
}

print("\(stores.count)") // If I break here for a given store that should contains multiple elements, I will see only the first one added in the else statement.

谁能告诉我我做错了什么?

最佳答案

如前所述,您将值(结构)语义与引用(类)语义混淆了。

一个简单的修复方法是将更改存储到以名称作为键的字典中:

var stores : Dictionary<String, Store> = [:]

并像这样使用它:

if(stores[store.name] == nil) {
stores[store.name] = store
}
else {
stores[storeName].bills.append(bill)
}

关于arrays - 在swift中找到后修改数组元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47318902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com