Home > Blockchain >  how to decode json from DeveloperPreview to enum decoder in swift
how to decode json from DeveloperPreview to enum decoder in swift

Time:12-17

I try to decode json from api, for this is use https://app.quicktype.io/

I parse my json response and get struct

This is my model :

struct Trait: Codable {
    let name: String
    let value: Value
    let filterable, visible, highlight: Bool
}

enum Value: Codable {
    case bool(Bool)
    case integer(Int)
    case string(String)

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let x = try? container.decode(Bool.self) {
            self = .bool(x)
            return
        }
        if let x = try? container.decode(Int.self) {
            self = .integer(x)
            return
        }
        if let x = try? container.decode(String.self) {
            self = .string(x)
            return
        }
        throw DecodingError.typeMismatch(Value.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Value"))
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .bool(let x):
            try container.encode(x)
        case .integer(let x):
            try container.encode(x)
        case .string(let x):
            try container.encode(x)
        }
    }
}

This is my preview provider :

let traits = Trait(
   name:"Style",
   value: Value(from: .bool),
   filterable:true,
   visible:true,
   highlight:true
)

this is the json (traits is list)

         "traits":[
            {
               "name":"Style",
               "value":"DD1399-105",
               "filterable":true,
               "visible":true,
               "highlight":true
            },
            {
               "name":"Colorway",
               "value":"White/Black-Total Orange",
               "filterable":true,
               "visible":true,
               "highlight":true
            },
            {
               "name":"Retail Price",
               "value":110,
               "filterable":true,
               "visible":true,
               "highlight":false
            },
            {
               "name":"Featured",
               "value":false,
               "filterable":false,
               "visible":false,
               "highlight":false
            }
         ],

I'm stuck here, I got some error because I don't know how to write a value in preview provider.

This is the error for the code above: error here

CodePudding user response:

You have to specify one of the enum cases with its associated value. Value(from: doesn't exist.

If you need a Bool it's either

let traits = Trait(
   name: "Style",
   value: .bool(true),
   filterable: true,
   visible: true,
   highlight: true
)

or

let traits = Trait(
   name: "Style",
   value: .bool(false),
   filterable: true,
   visible: true,
   highlight: true
)

CodePudding user response:

ok i think my first probleme is good but create a second one... This is my entiere Preview Provider :

class DeveloperPreview {

static let instance = DeveloperPreview()
init() { }

let sneaker = Sneakers(
     id:"7d37091c-f214-491a-a50c-d289f0f7e255",
     uuid:"7d37091c-f214-491a-a50c-d289f0f7e255",
     brand:"Nike",
     breadcrumbs:[
        
     ],
     browseVerticals:[
        "sneakers"
     ],
     category:"Nike Dunk",
     charityCondition:0,
     childID: JSONNull(),
     colorway:"White/Black-Total Orange",
     condition:"New",
     countryOfManufacture:"VN",
     dataType:"product",
     welcomeDescription: "welcom",
     hidden:false,
     listingType:"standard",
     minimumBid:25,
     gender:"men",
     doppelgangers:[
        
     ],
     media: Media(
        imageURL:"https://images.stockx.com/images/Nike-Dunk-Low-Black-White-2021.jpg?fit=fill&bg=FFFFFF&w=700&h=500&auto=format,compress&trim=color&q=90&dpr=2&updated_at=1624941957",
        smallImageURL:"https://images.stockx.com/images/Nike-Dunk-Low-Black-White-2021.jpg?fit=fill&bg=FFFFFF&w=300&h=214&auto=format,compress&trim=color&q=90&dpr=2&updated_at=1624941957",
        thumbURL:"https://images.stockx.com/images/Nike-Dunk-Low-Black-White-2021.jpg?fit=fill&bg=FFFFFF&w=140&h=100&auto=format,compress&trim=color&q=90&dpr=2&updated_at=1624941957",
        gallery:[
           
        ],
        hidden:false

     ),
     name:"Black White (2021)",
     productCategory:"sneakers",
     releaseDate:"",
     releaseTime:0,
     belowRetail:false,
     retailPrice:110,
     shoe:"Nike Dunk High",
     shortDescription:"Nike-Dunk-Low-Black-White-2021",
     styleID:"DD1399-105",
     tickerSymbol:"NK-NIDLFDXWB",
     title:"Nike Dunk High Black White (2021)",
     traits: [traits],
     type:0,
     urlKey:"nike-dunk-high-black-white-total-orange-2021",
     year:0,
     shoeSize: JSONNull(),
     market: Market(
        productID:0,
        skuUUID:"",
        productUUID:"7d37091c-f214-491a-a50c-d289f0f7e255",
        lowestAsk:173,
        lowestAskSize:"15",
        parentLowestAsk:0,
        numberOfAsks:196,
        hasAsks:1,
        salesThisPeriod:69,
        salesLastPeriod:0,
        highestBid:220,
        highestBidSize:"9.5",
        numberOfBids:230,
        hasBids:1,
        annualHigh:297,
        annualLow:67,
        deadstockRangeLow:238,
        deadstockRangeHigh:274,
        volatility:0.070391,
        deadstockSold:5891,
        pricePremium:1.627,
        averageDeadstockPrice:175,
        lastSale:256,
        lastSaleSize:"10.5",
        salesLast72Hours:69,
        changeValue:51,
        changePercentage:0.249544,
        absChangePercentage:0.249544,
        totalDollars:1029494,
        lastLowestAskTime:1639141012,
        lastHighestBidTime:1639160362,
        lastSaleDate:"2021-12-11T00:55:16 00:00",
        createdAt:"2021-06-29T04:46:03 00:00",
        updatedAt:1639184839,
        deadstockSoldRank:37,
        pricePremiumRank:1,
        averageDeadstockPriceRank:42,
        featured:0
     ),
     tags:[
        "sneakers",
        "nike",
        "nike",
        "dunk",
        "style_id|dd1399-105",
        "retail_price|110",
        "colorway|white/black-total orange"
     ],
     lockSelling:false,
     sellingCountries:[
        "AD",
        "AE",
        "US",
        "IN"
     ],
     buyingCountries:[
        "AD",
        "AE",
        "IN"
     ],
     objectID:"7d37091c-f214-491a-a50c-d289f0f7e255"
)

let traits = Trait(
   name:"Style",
   value: .bool(true),
   filterable:true,
   visible:true,
   highlight:true
)

and now i got this error : enter image description here

  • Related