title: Swift Firebase Reuse a function throughout the app
body: <p>In my app, in a few places I am loading data from Firebase Firestore database and showing the data. The problem is I am not adopting the DRY technique and I know I shouldn't, but I am reusing this same load function in different places in my app.</p>
  
  <pre><code>func loadData() {
  
          let user = Auth.auth().currentUser
          db.collection("users").document((user?.uid)!).collection("children").getDocuments() {
              QuerySnapshot, error in
              if let error = error {
                  print("\(error.localizedDescription)")
              } else {
                  // get all children into an array
                  self.childArray = QuerySnapshot!.documents.flatMap({Child(dictionary: $0.data())})
                  DispatchQueue.main.async {
                      self.childrenTableView.reloadData()
                  }
              }
          }
      }
  </code></pre>
  
  <p>The function simply grabs all the children from the database and adds them to my child array.</p>
  
  <p>Is there some better way to do this or a central place I can put this function where it can be called as and when I need it in the app instead of repeatedly adding it in multiple view controllers?</p>
  
  <p>I thought about a helper class, and just calling the function, but then not sure how to add the result to the childArray in the viewcontroller I needed it?</p>
  
  <hr>
  
  <p>my Child model</p>
  
  <pre><code>import UIKit
  import FirebaseFirestore
  
  
  protocol DocumentSerializable {
      init?(dictionary:[String:Any])
  }
  
  // Child Struct
  struct Child {
  
      var name: String
      var age: Int
      var timestamp: Date
      var imageURL: String
  
      var dictionary:[String:Any] {
          return [
              "name":name,
              "age":age,
              "timestamp":timestamp,
              "imageURL":imageURL
          ]
      }
  
  }
  
  //Child Extension
  extension Child : DocumentSerializable {
      init?(dictionary: [String : Any]) {
          guard let  name = dictionary["name"] as? String,
              let age = dictionary["age"] as? Int,
              let  imageURL = dictionary["imageURL"] as? String,
              let timestamp = dictionary["timestamp"] as? Date else {
                  return nil
          }
          self.init(name: name, age: age, timestamp: timestamp, imageURL: imageURL)
      }
  }
  </code></pre>