如何在 SwiftUI 中订阅数组的大小?

How can I subscribe to the size of an array in SwiftUI?

我想跟踪数组的大小,我认为这样的方法可行:

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。有更简洁的方法吗?

很难知道 CarRepositoryCarRepository.ownedCars 是什么,但我猜它们是这样的:

class CarRepositoryType: ObservableObject {
    @Published var ownedCars = []
}

var CarRepository = CarRepositoryType()

接收器在 ownedCars 更新之前被调用。新值传递给接收器;你应该在那里阅读。

    CarRepository.$ownedCars.sink { owned in
        self.ownedCarLength = owned.count
    }