这段代码是MVVM架构的正确实现吗?我想知道是否可以将下载的数组保留在私有(private)属性中以供将来在 TableView 中使用,或者我应该不惜一切代价避免这种情况?
代码:
import Foundation
class StopsViewModel {
weak var delegate: StopsViewModelDelegate?
private let dbService: DatabaseService
private var stops = [Stop]()
init(withDbService dbService: DatabaseService) {
self.dbService = dbService
}
func loadStops() {
dbService.getStops(completion: { [weak self] stops in
self?.stops = stops
self?.delegate?.getStopsCallFinished()
})
}
func getStop(atIndex index: Int) -> Stop {
return self.stops[index]
}
func getRowCount() -> Int {
return self.stops.count
}
func getSectionsCount() -> Int {
return 1
}
}
protocol StopsViewModelDelegate: class {
func getStopsCallFinished()
}
最佳答案
在与一些工作中的高级开发人员交谈后,他们告诉我,这是他们通常采取的方式。由于将数组保留在 View 模型中不会破坏 MVVM 模式,因此可以非常轻松地重用数据并清除数据服务以保留其他字段(使其更可重用)。
关于ios - 使用 Array 实现 Swift ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41663142/