1

Here is the JSON response I have.

Struct:

struct Welcome: Codable {
    let name: String
    let id: Int
}

JSON:

{
    "name": "Apple",
    "id": 23
}

This is the structure of JSON but the name will be null sometimes. So, I want to replace with default string value instead of null. Because to avoid app crash in future.

{
    "name": null,
    "id": 23
}

If the name is null then I want to give default value like "orange" for the property name only. I don't want to do anything with id.

I referred some SO answers are confusing and working with all properties in init instead of selected property. This is not possible for me because I have 200's of JSON properties with 50 types will be null or will have value..

How can I do it? Thanks in advance.

Mount Ain
  • 316
  • 3
  • 15

2 Answers2

2

You can (kind of) achieve that by making a wrapper:

struct Welcome: Codable {
    private let name: String? // <- This should be optional, otherwise it will fail decoding
    var defaultedName: String { name ?? "Orange" }

    let id: Int
}

This will also ensures that server never gets default value.

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
0

Needed to figure this out as well - the answer above is incomplete.

// Use a class
class Welcome: Codable {
  var name: String? // Optional property
  let id: Int

  enum WelcomeKeys: String, CodingKey {
    case name, id
  }

  // Implement the init function
  required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: WelcomeKeys.self)
    self.id = try container.decode(Int.self, forKey: .id)
    self.name = try container.decodeIfPresent(String.self, forKey: .name)
    if (self.name == nil ) {
      self.name = "orange"
    }
  }    
}