0

I have this piece of code:

struct NoteRecord: Codable {

let id: String
let title: String
let detail: String?
let dueDate: String?

private enum CodingKeys: String, CodingKey {
    case id, title, detail, dueDate
}}

and parsing part:

do {
     let decoder = JSONDecoder()
     let note = try decoder.decode(NoteRecord.self, from: data)

      } catch let err {
          print("Error occured:", err)
      }

Is there any way to use this when REST API returns an array of objects to decode the data correctly as array of structs?

1
  • Just remove the let theNote = … line. note will be initialised if the data is valid Commented May 18, 2018 at 13:56

2 Answers 2

2

Yes, just use this:

do {
     let decoder = JSONDecoder()
     let notes = try decoder.decode([NoteRecord].self, from: data)

      } catch let err {
          print("Error occured:", err)
      }

If you use [YourCodableStruct].self you are parsing the array. If you use YourCodableStruct.self you are parsing the struct.

Sign up to request clarification or add additional context in comments.

1 Comment

super easy, thanx
1

You can implement another struct to hold the array.

struct NoteRecords: Codable {
    var list: [NoteRecord] // You should change the var name and coding keys
}

And parse it like

let note = try decoder.decode(NoteRecords.self, from: data)

I hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.