我有一个通用的“执行”方法可以从网络上下载一些数据(省略了一些代码):
func perform<D: Decodable>(_ endPoint: EndPoint) -> AnyPublisher<D, APIProviderError> {
do {
let request = try requestBuilder.build(with: endPoint)
return try configurateSession(urlRequest: request, stub: endPoint.testData)
.dataTaskPublisher(for: request)
.decode(type: D.self, decoder: JSONDecoder())
catch {
fatalError(error.localizedDescription)
}
}
{
"layout": {
"id": "10",
"slots": [
{
"slotNumber": 1,
"widgets": [
{
"id":"10",
"type": "booking"
},
{
"id": "11",
"type": "banners"
},
{
"id":"12",
"type": "chips"
},
{
"id":"13",
"type": "products"
},
{
"id": "15",
"type": "banners"
}
]
}
并将其解析为结构数组
struct Container: Decodable {
let layout: Layout
}
struct Layout: Decodable {
let slots: [Slot]
}
struct Slot: Decodable {
let widgets: [Section]
}
struct Section: Decodable {
private enum CodingKeys: String, CodingKey {
case id, type
}
let id: String
let type: SectionType
var items: [Item]?
}
enum SectionType: String, Decodable {
case banners, brands, products, orders, coupons, map, card, booking, chips
}
{
"data": [
{
"offerPrice": "59.99",
"name": "ss",
"id": "60461"
},
{
"offerPrice": "79.99",
"name": "www",
"id": "60750"
}]
}
{
"data": [
{
"image": "url"
},
{
"image": "url",
"categoryId": "3074457345616766223"
}
]
}
到
struct ItemContainer<T: Decodable>: Decodable {
let id: String
let items: [T]
}
class Banner: Item, Decodable {
let categoryID: String?
let infoID: String?
let imageURL: String?
}
class Product: Item, Decodable {
let id: String
let name: String
let offerPrice: String
}
我认为,对于每个小部件,都有必要创建一个发布者。我不知道下一步该怎么做。邮编不适用于收藏集
我写了以下内容:
provider.perform(.structMain)
.map { (container: Container) in
container.layout.slots.first?.widgets
}.eraseToAnyPublisher()
.sink(receiveCompletion: { _ in
}, receiveValue: { result in
????????
})
.store(in: &self.cancellableset)
或者我还需要其他东西