1

I have next recursive Promise function call:

 func getPlaces(location: Location) -> Promise<[Geosearch]> {
   return Promise().then {
     URLSession.shared.dataTask(.promise, with: url)
   }.compactMap { result in
     let json = try JSONDecoder().decode(JsonPlaces.self, from: result.data)
     let places = json.query.geosearch
     return places
   }
 }

 func getAtLeastOnePlace(location: Location) -> Promise<[Geosearch]> {
   return getPlaces(location).then{ places in      //error here
     if hasNonVisitedPlaces(places: places) {
        return Promise.value(places)
     } else {
        return getPlaces(location)
     }
   }
 }

 func hasNonVisitedPlaces(places: [Geosearch]) -> Bool {
     return places.count > 0
 }

But compiler failed building with error "Cannot convert return expression of type 'Promise<_.T>' to return type 'Promise<[Geosearch]>'. Where is the mistake?


It seems like compiler error. This function has been compiled correctly:

 func getAtLeastOnePlace(location: Location) -> Promise<[Geosearch]> {
   return getPlaces(location).then{ places in                            
      return Promise.value(places)
   }
 }

This function too:

 func getAtLeastOnePlace(location: Location) -> Promise<[Geosearch]> {
   return getPlaces(location).then{ places in                            
      return getPlaces(location)
   }
 }

But this function caused an error:

 func getAtLeastOnePlace(location: Location) -> Promise<[Geosearch]> {
   return getPlaces(location).then{ places in      //error here
     if hasNonVisitedPlaces(places: places) {
        return Promise.value(places)
     } else {
        return getPlaces(location)
     }
   }
 }

1 Answers1

0

sometime we need to provide return type explicitly, so try below.

func getAtLeastOnePlace(location: Location) -> Promise<[Geosearch]> {
   return getPlaces(location).then{ places -> Promise<[Geosearch]> in
     if hasNonVisitedPlaces(places: places) {
        return Promise.value(places)
     } else {
        return getPlaces(location)
     }
   }
 }