Using Decodable to get the object and document ID with Firestore





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I have a simple User class which has the following fields:



{ 
"localIdentifier": "xyc9870",
"isOnline": false,
"username": "ZS"
}


I want to use Swift's Decodable to easily turn the QueryDocumentSnapshot into a type safe Swift struct. I also want to make sure that I get the documentID from the QueryDocumentSnapshot for updating the object later.



This is what I'm currently using to decode but obviously it misses the documentId



struct User: Decodable {

let localIdentifier: String
let username: String
let isOnline: Bool

}


Would love a hand here. Thanks!










share|improve this question





























    1















    I have a simple User class which has the following fields:



    { 
    "localIdentifier": "xyc9870",
    "isOnline": false,
    "username": "ZS"
    }


    I want to use Swift's Decodable to easily turn the QueryDocumentSnapshot into a type safe Swift struct. I also want to make sure that I get the documentID from the QueryDocumentSnapshot for updating the object later.



    This is what I'm currently using to decode but obviously it misses the documentId



    struct User: Decodable {

    let localIdentifier: String
    let username: String
    let isOnline: Bool

    }


    Would love a hand here. Thanks!










    share|improve this question

























      1












      1








      1








      I have a simple User class which has the following fields:



      { 
      "localIdentifier": "xyc9870",
      "isOnline": false,
      "username": "ZS"
      }


      I want to use Swift's Decodable to easily turn the QueryDocumentSnapshot into a type safe Swift struct. I also want to make sure that I get the documentID from the QueryDocumentSnapshot for updating the object later.



      This is what I'm currently using to decode but obviously it misses the documentId



      struct User: Decodable {

      let localIdentifier: String
      let username: String
      let isOnline: Bool

      }


      Would love a hand here. Thanks!










      share|improve this question














      I have a simple User class which has the following fields:



      { 
      "localIdentifier": "xyc9870",
      "isOnline": false,
      "username": "ZS"
      }


      I want to use Swift's Decodable to easily turn the QueryDocumentSnapshot into a type safe Swift struct. I also want to make sure that I get the documentID from the QueryDocumentSnapshot for updating the object later.



      This is what I'm currently using to decode but obviously it misses the documentId



      struct User: Decodable {

      let localIdentifier: String
      let username: String
      let isOnline: Bool

      }


      Would love a hand here. Thanks!







      swift firebase google-cloud-firestore






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 15:45









      Zack ShapiroZack Shapiro

      1,20194384




      1,20194384
























          1 Answer
          1






          active

          oldest

          votes


















          1














          I wrote myself a small convenience extension that just brings the documentID into the data JSON and then I can use the simple struct below



          extension QueryDocumentSnapshot {

          func prepareForDecoding() -> [String: Any] {
          var data = self.data()
          data["documentId"] = self.documentID

          return data
          }

          }


          Decode using:



          struct User: Decodable {

          let documentId: String
          let localIdentifier: String
          let username: String
          let isOnline: Bool

          }

          if let user = try? JSONDecoder().decode(User.self, fromJSONObject: doc.prepareForDecoding()) {
          ...
          }


          Edit:



          My JSONDecoder extension



          extension JSONDecoder {
          func decode<T>(_ type: T.Type, fromJSONObject object: Any) throws -> T where T: Decodable {
          return try decode(T.self, from: try JSONSerialization.data(withJSONObject: object, options: ))
          }
          }





          share|improve this answer


























          • Hi Zack, there is no method fromJSONObject of JSONDecoder(). How can you decode it?

            – Asif Raza
            Nov 20 '18 at 9:37











          • Asif, I just added my extension that allows me to do this

            – Zack Shapiro
            Nov 20 '18 at 20:24












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53341137%2fusing-decodable-to-get-the-object-and-document-id-with-firestore%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          I wrote myself a small convenience extension that just brings the documentID into the data JSON and then I can use the simple struct below



          extension QueryDocumentSnapshot {

          func prepareForDecoding() -> [String: Any] {
          var data = self.data()
          data["documentId"] = self.documentID

          return data
          }

          }


          Decode using:



          struct User: Decodable {

          let documentId: String
          let localIdentifier: String
          let username: String
          let isOnline: Bool

          }

          if let user = try? JSONDecoder().decode(User.self, fromJSONObject: doc.prepareForDecoding()) {
          ...
          }


          Edit:



          My JSONDecoder extension



          extension JSONDecoder {
          func decode<T>(_ type: T.Type, fromJSONObject object: Any) throws -> T where T: Decodable {
          return try decode(T.self, from: try JSONSerialization.data(withJSONObject: object, options: ))
          }
          }





          share|improve this answer


























          • Hi Zack, there is no method fromJSONObject of JSONDecoder(). How can you decode it?

            – Asif Raza
            Nov 20 '18 at 9:37











          • Asif, I just added my extension that allows me to do this

            – Zack Shapiro
            Nov 20 '18 at 20:24
















          1














          I wrote myself a small convenience extension that just brings the documentID into the data JSON and then I can use the simple struct below



          extension QueryDocumentSnapshot {

          func prepareForDecoding() -> [String: Any] {
          var data = self.data()
          data["documentId"] = self.documentID

          return data
          }

          }


          Decode using:



          struct User: Decodable {

          let documentId: String
          let localIdentifier: String
          let username: String
          let isOnline: Bool

          }

          if let user = try? JSONDecoder().decode(User.self, fromJSONObject: doc.prepareForDecoding()) {
          ...
          }


          Edit:



          My JSONDecoder extension



          extension JSONDecoder {
          func decode<T>(_ type: T.Type, fromJSONObject object: Any) throws -> T where T: Decodable {
          return try decode(T.self, from: try JSONSerialization.data(withJSONObject: object, options: ))
          }
          }





          share|improve this answer


























          • Hi Zack, there is no method fromJSONObject of JSONDecoder(). How can you decode it?

            – Asif Raza
            Nov 20 '18 at 9:37











          • Asif, I just added my extension that allows me to do this

            – Zack Shapiro
            Nov 20 '18 at 20:24














          1












          1








          1







          I wrote myself a small convenience extension that just brings the documentID into the data JSON and then I can use the simple struct below



          extension QueryDocumentSnapshot {

          func prepareForDecoding() -> [String: Any] {
          var data = self.data()
          data["documentId"] = self.documentID

          return data
          }

          }


          Decode using:



          struct User: Decodable {

          let documentId: String
          let localIdentifier: String
          let username: String
          let isOnline: Bool

          }

          if let user = try? JSONDecoder().decode(User.self, fromJSONObject: doc.prepareForDecoding()) {
          ...
          }


          Edit:



          My JSONDecoder extension



          extension JSONDecoder {
          func decode<T>(_ type: T.Type, fromJSONObject object: Any) throws -> T where T: Decodable {
          return try decode(T.self, from: try JSONSerialization.data(withJSONObject: object, options: ))
          }
          }





          share|improve this answer















          I wrote myself a small convenience extension that just brings the documentID into the data JSON and then I can use the simple struct below



          extension QueryDocumentSnapshot {

          func prepareForDecoding() -> [String: Any] {
          var data = self.data()
          data["documentId"] = self.documentID

          return data
          }

          }


          Decode using:



          struct User: Decodable {

          let documentId: String
          let localIdentifier: String
          let username: String
          let isOnline: Bool

          }

          if let user = try? JSONDecoder().decode(User.self, fromJSONObject: doc.prepareForDecoding()) {
          ...
          }


          Edit:



          My JSONDecoder extension



          extension JSONDecoder {
          func decode<T>(_ type: T.Type, fromJSONObject object: Any) throws -> T where T: Decodable {
          return try decode(T.self, from: try JSONSerialization.data(withJSONObject: object, options: ))
          }
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 20 '18 at 20:24

























          answered Nov 16 '18 at 16:05









          Zack ShapiroZack Shapiro

          1,20194384




          1,20194384













          • Hi Zack, there is no method fromJSONObject of JSONDecoder(). How can you decode it?

            – Asif Raza
            Nov 20 '18 at 9:37











          • Asif, I just added my extension that allows me to do this

            – Zack Shapiro
            Nov 20 '18 at 20:24



















          • Hi Zack, there is no method fromJSONObject of JSONDecoder(). How can you decode it?

            – Asif Raza
            Nov 20 '18 at 9:37











          • Asif, I just added my extension that allows me to do this

            – Zack Shapiro
            Nov 20 '18 at 20:24

















          Hi Zack, there is no method fromJSONObject of JSONDecoder(). How can you decode it?

          – Asif Raza
          Nov 20 '18 at 9:37





          Hi Zack, there is no method fromJSONObject of JSONDecoder(). How can you decode it?

          – Asif Raza
          Nov 20 '18 at 9:37













          Asif, I just added my extension that allows me to do this

          – Zack Shapiro
          Nov 20 '18 at 20:24





          Asif, I just added my extension that allows me to do this

          – Zack Shapiro
          Nov 20 '18 at 20:24




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53341137%2fusing-decodable-to-get-the-object-and-document-id-with-firestore%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Xamarin.iOS Cant Deploy on Iphone

          Glorious Revolution

          Dulmage-Mendelsohn matrix decomposition in Python