1

I am trying to adapt Swift 4 Decodable to the JSON created by my Firebase database:

{
  "sections" : {
    "-KxVQoo6ElOVhoFliQ5s" : {
      "details" : "Residents",
      "row" : "0",
      "section" : "0",
      "task" : "Do evals"
    },
    "-KxVQooF5rNNNOKrlXT9" : {
      "details" : "Phone",
      "row" : "0",
      "section" : "1",
      "task" : "Do bills"
    }
  }
}

Firebase creates new uniqueID when elements are added by autoID. I am trying to create an object that will allow me to store the Firebase JSON data. In all examples online, there are always names and values shown. In the case above, the uniqueID is just the value. I am looking for how to create a class that can be used to decode the data when there is only a unique value.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
OlderCoder
  • 11
  • 1

1 Answers1

2

When your keys are dynamic, a Dictionary might be a better fit. For instance:

struct Data: Decodable {
  var sections: [String: Element]
}

and then define your Element type as usual:

struct Element: Decodable {
  var details: String
  var row: String
  var section: String
  var task: String
}

Always worth remembering that a Dictionary is a Decodable type too (as long as its keys and values are decodable as well).

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
  • 1
    @OlderCoder Hey man, if this fixed your issue be sure to mark it as the *accepted answer* when you get a chance. Thanks and welcome to SO! – Paulo Mattos Nov 01 '17 at 11:35