不同类型的 RxSwift

Different types RxSwift

我不知道如何映射自定义类型。我有两个自定义类型的变量 -

var 视图模型:PurchaseList.Fetch.ViewModel? 变量响应: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 response: PurchaseList.Fetch.Response? 创建 var viewModel: PurchaseList.Fetch.ViewModel?

根据您提供的类型,我猜您正在寻找类似于下面的代码。由于在类型中过度使用了 Optionals(?),这段代码有很多偶然的复杂性。

实际上没有理由将字符串或数组设为可选。从逻辑上讲,在 99.99% 的情况下,空字符串与 nil 字符串没有区别(空数组与 nil 数组没有区别)。因此,需要提出强有力的论据来证明将它们设为可选。

func example(_ from: Observable<Response?>) -> Observable<[ViewModel]?> {
    return from
        .map { [=10=]?.shoppingList ?? [] }
        .map { [=10=].map{ [=10=].map(ViewModel.init) } }
}

extension ViewModel {
    init(_ shoppingList: ShoppingList) {
        name = shoppingList.name
        offers = shoppingList.offers?.map { ViewModelOffers(fullPrice: [=10=].fullPrice) }
    }
}