隐藏模型层有优势吗?[关闭]

Is there an advantage to hiding the model layer? [closed]

提问人:Ariel Antonio Fundora 提问时间:11/17/2023 最后编辑:Ariel Antonio Fundora 更新时间:11/17/2023 访问量:75

问:


想改进这个问题吗?更新问题,以便可以通过编辑这篇文章用事实和引文来回答。

2天前关闭。

我正在看一个关于MVVM架构模式的教程。

它说视图永远不应该直接访问模型。因此,所有模型始终隐藏在视图模型后面。

例如:

struct Location: Codable, Equatable {

//MARK: Properties

let id: String
let name: String
let country: String

//
let latitude: Double
let longitude: Double

init(id: String, name: String, country: String, latitude: Double, longitude: Double) {
    self.id = id
    self.name = name
    self.country = country
    self.latitude = latitude
    self.longitude = longitude
}
}

查看隐藏模型图层的模型

final class LocationCellViewModel: Identifiable {

//MARK: Properties

private let location: Location

//
var locationViewModel: LocationViewModel {
    .init(location: location)
}

// MARK: - Initialization

init(location: Location) {
    self.location = location
}

// MARK: - Public API

var locationName: String {
    location.name
}

var locationCountry: String {
    location.country
}

....

}

将作为属性出现在视图中的视图模型

final class LocationsViewModel {

//MARK: Properties

private(set) var locationCellViewModels: [LocationCellViewModel] = []

   ....

 }

为什么在 LocationsViewModel 类中使用 LocationCellViewModel 数组而不是 Location 数组会更好?这样做有什么好处吗?

iOS Swift SwiftUI 设计模式 MVVM

评论


答: 暂无答案