【发布时间】:2020-02-10 21:47:42
【问题描述】:
我正在开发一个使用 GraphQL 从 shopify 商店获取产品信息的项目。 我通过搜索产品 ProductID 来查询数据,并以 Storefront.Product 的形式获取数据。 但是,我的视图模型要求它采用 Storefront.ProductEdge 的形式。
我试图在同一个视图模型 (ProductViewModel) 中添加两种不同的模型类型(Storefront.Product 和 Storefront.ProductEdge)。
这是我的代码:
import Foundation
import Buy
final class ProductViewModel: ViewModel {
typealias ModelType = Storefront.ProductEdge
typealias ModelType1 = Storefront.Product
let model: ModelType
let model1: ModelType1
let cursor: String
var id: String
var title: String
var summary: String
var price: String
var images: PageableArray<ImageViewModel>
var variants: PageableArray<VariantViewModel> ///Ive changed let to var here so i can assign values in HomeController
// ----------------------------------
// MARK: - Init -
//
required init(from model: ModelType) {
self.model = model
self.cursor = model.cursor
let variants = model.node.variants.edges.viewModels.sorted {
$0.price < $1.price
}
let lowestPrice = variants.first?.price
self.id = model.node.id.rawValue
self.title = model.node.title
self.summary = model.node.descriptionHtml
self.price = lowestPrice == nil ? "No price" : Currency.stringFrom(lowestPrice!)
self.images = PageableArray(
with: model.node.images.edges,
pageInfo: model.node.images.pageInfo
)
self.variants = PageableArray(
with: model.node.variants.edges,
pageInfo: model.node.variants.pageInfo
)
}
required init(from model1: ModelType1){
self.model1 = model1
self.cursor = ""
let variants = model1.variants.edges.viewModels.sorted {
$0.price < $1.price
}
let lowestPrice = model1.variants.edges.first?.viewModel.price
self.id = model1.id.rawValue
self.title = model1.title
self.summary = model1.descriptionHtml
self.price = lowestPrice == nil ? "No price" : Currency.stringFrom(lowestPrice!)
self.images = PageableArray(
with: model1.images.edges,
pageInfo: model1.images.pageInfo
)
self.variants = PageableArray(
with: model1.variants.edges,
pageInfo: model1.variants.pageInfo
)
}
}
extension Storefront.ProductEdge: ViewModeling {
typealias ViewModelType = ProductViewModel
}
这是在说
Return from initializer without initializing all stored properties
这可能吗?
请帮忙?
编辑:
通过制作模型和模型1选项或在模型或模型1上使用枚举,我得到了错误
Type 'ProductViewModel' does not conform to protocol 'ViewModel'
我是否需要以某种方式在 Storefront.ProductEdge 和 Storefront.Product 上执行 If 语句或枚举??
这里是 ViewModel 协议:
import Foundation
protocol ViewModel: Serializable {
associatedtype ModelType: Serializable
var model: ModelType { get }
init(from model: ModelType)
}
extension ViewModel {
static func deserialize(from representation: SerializedRepresentation) -> Self? {
if let model = ModelType.deserialize(from: representation) {
return Self.init(from: model)
}
return nil
}
func serialize() -> SerializedRepresentation {
return self.model.serialize()
}
}
。我无法更改此协议。
请帮忙?
【问题讨论】:
标签: ios swift xcode mvvm graphql