我想返回一个函数,该函数又会回调自身。 是否可以通过返回一个调用自身的闭包来实现?
我的问题是我不确定在这里使用正确的语法,而且我不确定它是否可能因为对自身的循环引用(并且 swift 对编译器类型检查很重要)
我正在柯里化(Currying)我的函数,这样模型和演示者就不需要知道 dataGateway 进一步解耦我的代码
有关该问题的一些背景信息,API 需要将页码传递给自身,我不想存储此状态。我希望函数传回一些东西,以便模型可以在需要时调用下一个函数。
我知道柯里化(Currying)函数定义是这样的:
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 })
}
}
思路一——以元组形式返回
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
}
向下滚动到 TableView 底部会再次触发上述操作,使用 next
函数而不是 data
关于ios - Swift:返回递归函数(currying),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32863982/