【发布时间】:2021-05-17 17:28:35
【问题描述】:
我有以下型号
final class Vehicle {
var cars:[SportsCar] = []
}
final class SportsCar {
var isCheap:Bool = false
}
假设 Vehicle 和 SportsCar 都是 Equatable(为简单起见,我省略了 Equatable 一致性)。
目标:更新嵌入在 Vehicles BehaviorRelay 继电器内的汽车数组中的汽车之一的 isCheap 属性。
尝试:
final class ViewModel {
let vehicles:BehaviorRelay<[Vehicle]> = BehaviorRelay(value: [])
// Attempt 1: Access vehicles direct without making a copy.
// Toggling `isCheap` property when user tap a button on a collectionView cell.
func updateCarProperty(checkedVehicle:Vehicle,checkedIndexPath:IndexPath){
for car in vehicles.value[checkedIndexPath.section].cars {
let checkedCar = checkedVehicle.cars[checkedIndexPath.item]
if car == checkedCar {
if car.isCheap {
vehicles.value[checkedIndexPath.section].cars[checkedIndexPath.item].isCheap = false
}else {
vehicles.value[checkedIndexPath.section].districts[checkedIndexPath.item].isCheap = true
}
break
}
}
}
}
// Attempt 2: Make a copy of vehicles then use it to change the property then on completion update the whole vehicles array by calling
//vehicles.accept(vehiclesCopy)
// As described on this answer: https://stackoverflow.com/a/58295908/7551807
// This approach didn't work too.
期望:当函数调用完成时,Car isCheap 属性会改变。
结果:该属性没有按预期更改????。无论如何,它都保持为默认值(false)!!
问题:还有其他更好的方法来处理这个问题吗?
【问题讨论】: