0
struct Data: Codable {
  let name: String?
  let dataArray: [User] = [User]()
}

dataArray is optional so I want to allocate it with empty but my Codable is failing? Can I know How can achieve this, I can declare it as Optional without allocating it. But I want to achieve this.

AppleBee
  • 452
  • 3
  • 16
  • 1
    there is no meaning to allocate it , why not simply check if it's not nil or use `?? []` where you actually use it – Shehata Gamal Nov 28 '19 at 09:31
  • 3
    Does this answer your question? [Swift codable, Default Value to Class property when key missing in the JSON](https://stackoverflow.com/questions/53237085/swift-codable-default-value-to-class-property-when-key-missing-in-the-json) – Joakim Danielson Nov 28 '19 at 09:41
  • I see good answers. But also, `dataArray` is a `let`. You're already assigning it, which can't be changed later. – Jeroen Nov 28 '19 at 09:52

2 Answers2

4

You should decode your object manually:

struct Data: Codable {
  let name: String?
  let dataArray: [User]

   enum Keys: String, CodingKey {
              case name
              case dataArray
   }          

   init(from decoder: Decoder) throws {
       let container = try decoder.container(keyedBy: Keys.self)
        name = try? container.decode(String.self, forKey: .name)
        dataArray =  (try? container.decode(User, forKey: . dataArray)) ?? []
    }
}

Or you can create a wrapper :

struct Data: Codable {
  let name: String?
  private let _dataArray: [User]?

  var dataArray : [User] {
      get {
        return   _dataArray ?? []
      }
   }

   enum Keys: String, CodingKey {
                case name
                case dataArray
   }
}
Anjali Shah
  • 720
  • 7
  • 21
CZ54
  • 5,488
  • 1
  • 24
  • 39
  • 1
    For `dataArray` it should be `decodeIfPresent` with a hard `try`. Because you want default value only iff it's not in JSON. And want to get the error if something else happened, like `dataArray` is there, but type is wrong. Also, `wrapper` options will fail to parse, `dataArray` coding key still refers to Read-Only variable. – user28434'mstep Nov 28 '19 at 09:57
-1

Let's suppose it is a User Model:

struct User : Codable {
    let userName: String?
}

struct Data: Codable {
   let name: String?
   //Optional Array
   let dataArray: [User]?
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Chaman Sharma
  • 641
  • 5
  • 10