![](/img/trans.png)
[英]Swift: What is the difference between 'Currying' and the function that return a function?
[英]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 })
}
}
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))
}
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.