使用rxswift的多个地图

时间:2018-12-31 12:52:03

标签: ios swift reactive-programming rx-swift

我试图从一个项目数组创建一个tableview的节,每个数组项目都是一个节项目。

  

我的问题是如何使cart.map返回一个数组
  CartProductSection([CartProductSection])而不是将其分配给变量。谢谢。

我的代码     让购物车:BehaviorRelay  struct输出{         让项目:Observable <[CartProductSection]>     }

           var sectionPerSupplierItems: [CartProductSection] = []

            _ = cart.map { (cart)  in 
                let cartItemsPerSupplier = self.sortModelItemPerSection(items: cart.items)

                print(cart.items.count)
                 _ = cartItemsPerSupplier.map {  (cartItemsPerSupplier) in

                    var items: [CartProductSectionItem] = []
                    for cartItem in cartItemsPerSupplier.cartItems {
                         items.append(CartProductSectionItem.cartItem(viewModel: CartItemViewModel(with: cartItem)))
                    }

                    sectionPerSupplierItems.append(CartProductSection.cartItemModel
(title: cartItemsPerSupplier.companyName, items: items))
                }
            }

            return Output(items: Observable.just(sectionPerSupplierItems))

1 个答案:

答案 0 :(得分:1)

我可能会像这样编写代码(我仍然在这里做一堆假设。):

let items = cart
    .map { [unowned self] in self.sortModelItemPerSection(items: $0.items) }
    .map { cartItemsPerSuppliers in
        cartItemsPerSuppliers.map { CartProductSection.cartItemModel(from: $0) }
    }
return Output(items: items)

以上假设存在类似的东西:

extension CartProductSection {
    static func cartItemModel(from supplier: CartItemsPerSupplier) -> CartProductSection {
        return cartItemModel(title: supplier.companyName, items: supplier.cartItems.map { CartProductSectionItem.cartItem(viewModel: CartItemViewModel(with: $0)) })
    }
}