我想跟踪数组的大小,我认为这样的东西会起作用:
class CarListViewModel: ObservableObject {
private var cancellables = Set<AnyCancellable>()
@Published var ownedCarLength = 0
init(){
CarRepository.$ownedCars.sink { _ in
self.ownedCarLength = CarRepository.ownedCars.count
}
.store(in: &cancellables)
}
因为每次修改数组CarRepository.ownedCars
时都会调用此函数,但是由于某种原因,从CarRepository.ownedCars.count返回的值计算为0。有更干净的方法吗?
很难知道CarRepository
和CarRepository.ownedCars
是什么,但我猜它们是这样的:
class CarRepositoryType: ObservableObject {
@Published var ownedCars = []
}
var CarRepository = CarRepositoryType()
在更新ownedCars
之前调用接收器。将新值传递给接收器;你应该在那里读。
CarRepository.$ownedCars.sink { owned in
self.ownedCarLength = owned.count
}