【问题标题】:Why recursive PromiseKit functions cannot be compiled?为什么无法编译递归 PromiseKit 函数?
【发布时间】:2023-03-11 20:49:02
【问题描述】:

我有下一个递归 Promise 函数调用:

 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
 }

但是编译器构建失败,出现错误“无法将'Promise<_.t>'类型的返回表达式转换为'Promise'类型。错误在哪里?


这似乎是编译器错误。 该函数已正确编译:

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

这个功能也是:

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

但是这个函数导致了错误:

 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)
     }
   }
 }

【问题讨论】:

  • 错误出现在哪一行?
  • 已更新错误行标记

标签: ios swift recursion promisekit


【解决方案1】:

有时我们需要显式地提供返回类型,所以试试下面。

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)
     }
   }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    相关资源
    最近更新 更多