I try to decode json from api, for that i use this website : https://app.quicktype.io/
this is my json from api :
{
"id":"7d37091c-f214-491a-a50c-d289f0f7e255",
"uuid":"7d37091c-f214-491a-a50c-d289f0f7e255",
"brand":"Nike",
"breadcrumbs":[
],
"browseVerticals":[
"sneakers"
],
"category":"Nike Dunk",
"charityCondition":0,
"childId":null,
"colorway":"White/Black-Total Orange",
"condition":"New",
"countryOfManufacture":"VN",
"dataType":"product",
"description":"",
"hidden":false,
"listingType":"standard",
"minimumBid":25,
"gender":"men",
"doppelgangers":[
],
"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":[
{
"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
}
],
"type":0,
"urlKey":"nike-dunk-high-black-white-total-orange-2021",
"year":0,
"shoeSize":null,
"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"
],
"lock_selling":false,
"selling_countries":[
"AD",
"AE",
],
"buying_countries":[
"AD",
"AE",
"ES",
"US",
"XK",
"IC",
"IN"
],
"objectID":"7d37091c-f214-491a-a50c-d289f0f7e255"
}
this is my 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 this is my decoder :
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)
}
}
}
My error come from the preview provider :
"Cannot use instance member 'traits' within property initializer; property initializers run before 'self' is available"
CodePudding user response:
The error is exactly pointed out by compiler. Converting from API response, this should work as expected on error snippet.
traits: [
Trait(
name:"Style",
value: .string("DD1399-105"),
filterable:true,
visible:true,
highlight:true
),
Trait(
name:"Colorway",
value: .string("White/Black-Total Orange"),
filterable:true,
visible:true,
highlight:true
),
Trait(
name:"Retail Price",
value: .integer(110),
filterable:true,
visible:true,
highlight:false
),
Trait(
name:"Featured",
value: .bool(false),
filterable:false,
visible:false,
highlight:false
)
],
CodePudding user response:
You cannot initialize properties which depend on each other on the top level of a class, you have to create the trait inside let sneaker = Sneakers( ...
Replace
traits: [traits],
with
traits: [Trait(
name:"Style",
value: .bool(true),
filterable:true,
visible:true,
highlight:true)],