我不知道如何映射自定义类型。我有两个具有自定义类型的变量-
var viewModel:PurchaseList.Fetch.ViewModel?var回应:PurchaseList.Fetch.Response?
struct Response: Mappable {
var shoppingList : [ShoppingList]?
}
struct ShoppingList: Mappable {
var name: String?
var offers: [Offers]?
}
struct Offers {
var fullPrice: String?
}
和
struct ViewModel {
var name: String?
var offers: [ViewModelOffers]?
}
struct ViewModelOffers {
var fullPrice: String?
}
如何使用RxSwift从var viewModel: PurchaseList.Fetch.ViewModel?
创建var response: PurchaseList.Fetch.Response?
?
根据您提供的类型,我猜您正在寻找类似下面的代码。由于在类型中过度使用了Optionals(?
),因此该代码具有很多偶然的复杂性。
几乎没有理由将字符串或数组设为可选。逻辑上,在99.99%的情况下,空字符串与nil字符串相同(空数组与nil数组相同)。因此,需要提出一个强有力的论据来证明使它们成为可选项是合理的。
func example(_ from: Observable<Response?>) -> Observable<[ViewModel]?> {
return from
.map { $0?.shoppingList ?? [] }
.map { $0.map{ $0.map(ViewModel.init) } }
}
extension ViewModel {
init(_ shoppingList: ShoppingList) {
name = shoppingList.name
offers = shoppingList.offers?.map { ViewModelOffers(fullPrice: $0.fullPrice) }
}
}