Luda
Luda

Reputation: 7068

Failable Initializers with Codable

I'm attempting to parse the following json schema of array of items, itemID may not be empty. How do I make an item nil id itemID does not exist in the JSON?

[{
    "itemID": "123",
    "itemTitle": "Hello"
  },
  {},
  ...
]

My decodable classes are as follows:

public struct Item: : NSObject, Codable {
    let itemID: String
    let itemTitle: String?
}

private enum CodingKeys: String, CodingKey {
    case itemID
    case itemTitle
}

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        itemID = try container.decode(String.self, forKey: .itemID)
        itemTitle = try container.decodeIfPresent(String.self, forKey: .itemTitle)

        super.init()
    }
}

Upvotes: 1

Views: 612

Answers (1)

PGDev
PGDev

Reputation: 24341

First of all, itemID is an Int and not String in your JSON response. So the struct Item looks like,

public struct Item: Codable {
    let itemID: Int?
    let itemTitle: String?
}

Parse the JSON like,

if let data = data {
    do {
        let items = try JSONDecoder().decode([Item].self, from: data).filter({$0.itemID == nil})
        print(items)
    } catch {
        print(error)
    }
}

In the above code you can simply filter out the items with itemID == nil.

Upvotes: 1

Related Questions