Search code examples
swiftapistructcodable

Swift 5 Codable - API provides sometimes an value sometimes not


I have Codables running now. But from API sometime Example Was Coming and sometimes example was not coming. I was searching here and found this

below are images with example element or without example elemnt

With Example enter image description here

Without example enter image description here

i have created structure for this but this is not work. because example was coming or

struct Defination: Codable {
var definition: String
var synonyms: [String]
var antonyms: [String]
var example: String

enum CodingKeys: String, CodingKey {
    case definition
    case synonyms
    case antonyms
    case example
}

}


Solution

  • you can create like this type structure, if you have a any value are sometime coming or sometime not coming so that value you write like this.

    var example: String?

    only write ? end of the DataType

    this answer given by @Shadowrun