0

I am using Swift. I have the following fetchData() method in my view model:

func fetchData() {
    donorsRepository.fetchData()
    donor = donorsRepository.donor
}

As you can see, inside the method body, another fetchData() method is called on my repository. The donor property on my view model should then be assigned to the repository's donor property. the problem is that this needs to happen after the repository's fetchData() method has completed. So I need to capture the line "donor = repository.donor" inside a closure. How do I do that?

I tried writing the closure like this:

func fetchData() {
    donorsRepository.fetchData() { donor in
        self.donor = donorsRepository.donor }
}

But it gave me an error in the first line of the method body, saying "Extra trailing closure passed in call".

MartinG
  • 1
  • 2
  • 1
    donorsRepository.fetchData() needs to be declared to take that closure as an argument so that the function can call the closure. Or skip closures and use async/await. – Joakim Danielson Mar 14 '23 at 14:55
  • Thanks @Joakim Danielson. How would I write that closure as an argument in donorsRepository.fetchData()? – MartinG Mar 14 '23 at 15:01
  • Something like `func fetchData(completion: (DonorsType) -> Void)` – Joakim Danielson Mar 14 '23 at 15:06
  • I modified the method to be the following: func fetchData(completion: ([Donor]) -> Void) { // method body } Is that correct? Also, is my closure being called? I think that maybe it isn't? In which case, where do I call the closure? I added the following method call to the body of the donorsRepository.fetchData() method: completion(donor) Is that correct? – MartinG Mar 15 '23 at 10:09
  • It should perhaps be `func fetchData(completion: (Donor) -> Void)` since in the example you posted it looks like you pass one object but if it is an array then your version is fine. – Joakim Danielson Mar 15 '23 at 14:29

0 Answers0