繁体   English   中英

Swift:返回递归函数(循环)

[英]Swift: Returning a recursive function (currying)

我想返回一个函数,该函数将依次回调自身。 是否可以通过返回一个闭包来实现呢?

我的问题是我不确定在这里使用的正确语法,也不确定是否有可能由于对自身的循环引用(并且迅速进行编译器类型检查)

我使用了我的函数,因此模型和演示者无需了解dataGateway进一步分离我的代码

有关此问题的一些背景信息,API希望将页码传递给自身,我不想存储此状态。 我希望函数传回一些信息,以便模型可以在需要时调用下一个函数。

我知道咖喱函数的定义是这样的:

function    (completion: ([Example.Product], UInt) -> Void) -> Example.Task?

在我的代码示例中寻找__function_defined_here__

原始-示例代码

func fetch(dataGateway: DataGateway, category: String)(page: UInt)(completion: [Product] -> Void) -> Task? {

  return dataGateway.productMap(category, page: page) { products in
    completion(products.map { $0.build })
  }

}

想法1-以元组形式返回

func fetch(dataGateway: DataGateway, category: String)(page: UInt)(completion: [Product] -> Void) -> (Task?, __function_defined_here__) {

  return (dataGateway.productMap(category, page: page) { products in
    completion(products.map { $0.build })
  }, fetch(dataGateway, category: category)(page: page + 1))

}

想法2-完成时返回

func fetch(dataGateway: DataGateway, category: String)(page: UInt)(completion: ([Product], __function_defined_here__) -> Void) -> Task? {

  return dataGateway.productMap(category, page: page) { products in
    completion(products.map { $0.build }, fetch(dataGateway, category: category)(page: page + 1))
  }

}

我最终用以下类似的方法解决了该问题,它的工作是创建一个类引用以存储下一个函数。在异步操作完成时,我将该对象传递给该对象。

extension Product {
  class Next {

    typealias FunctionType = (([Product], Next) -> Void) -> Task?
    let fetch: FunctionType

    init(_ fetch: FunctionType) {
      self.fetch = fetch
    }

  }

  func fetch(dataGateway: DataGateway, inCategory category: String)(page: UInt)(completion: ([Product], Next) -> Void) -> Task? {

    return dataGateway.products(inCategory: category, page: page)() { products in
      completion(products.map { $0.build }, Next(fetch(dataGateway, inCategory: category)(page: page + 1)))
    }

  }
}


let initial = Product.fetch(dataGateway, inCategory: "1")(page: 0)

将函数传递给数据模型

data() { [weak self] products, next in 
  self?.data = products
  self?.setNeedsUpdate()
  self?.next = next
}

向下滚动到表格视图的底部,使用next函数代替data再次触发以上操作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM