-1

Trying to figure out how to return the results of my codeable json data from my func.

class Service {
static let shared = Service()
let BASE_URL = "xxx"

func fetchClient(completion: @escaping ([Client]) -> ()) {
    var clientArray = [Client]()

    guard let url = URL(string: BASE_URL) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, error) in

        // handle error
        if let error = error {
            print("Failed to fetch data with error: ", error.localizedDescription)
            return
        }

        guard let data = data else {return}

        do {
            let clients = try JSONDecoder().decode([Client].self, from: data)
            clientArray.append(clients)????

        } catch let error {
            print("Failed to create JSON with error: ", error.localizedDescription)
        }
    }.resume()
}
}

I know that I can't append clients directly to clientArray, as it is an Array itself, but i am unsure how to go about unpacking it so that the func returns the data properly? thanks

Flimzy
  • 68,325
  • 15
  • 126
  • 165
Anthony
  • 872
  • 6
  • 19

1 Answers1

0

You don't need var clientArray = [Client]().

replace clientArray.append(clients)???? with completion(clients)

Kirow
  • 976
  • 8
  • 23