【问题标题】:Pass additional parameters to completion handler without curried function?将附加参数传递给没有咖喱函数的完成处理程序?
【发布时间】:2016-05-04 06:35:46
【问题描述】:

我刚刚打开了一个很久没有修改过的项目,并注意到一个警告:“在未来的 Swift 版本中将删除 Curried 函数声明语法;使用单个参数列表”。

我不太确定在这种情况下如何抢先删除我的咖喱函数(这对我来说似乎是完美的解决方案)。我目前正在使用一个将其他参数传递给完成处理程序。

func getCoursesForProfile(profileName: String, pageNumber: Int) {
    if let url = NSURL(string:profileBaseURL + profileName + pageBase + String(pageNumber)) {
        let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: parseSessionCompletion(profileName, pageNumber: pageNumber))

        task.resume()
    }
}

func parseSessionCompletion(profileName: String, pageNumber: Int)(data: NSData?, response: NSURLResponse?, error: NSError?) {

我的问题:有没有办法完成柯里化的移除,同时仍然具有解析“已完成会话”的可重用函数?

我想到的唯一“简单”方法是拥有一个类的不同实例并将 profileName/pageNumber 保留在函数范围之外。但这在多种方面似乎很浪费。

【问题讨论】:

    标签: swift currying


    【解决方案1】:

    柯里化并没有被移除——它只是用于定义一个被移除的柯里化函数的便利语法。现在你必须定义一个柯里化函数显式返回另一个函数(单个参数列表)。

    例如,在你的情况下,你会想要这样的东西:

    func parseSessionCompletion(profileName: String, pageNumber: Int) -> (data: NSData?, response: NSURLResponse?, error: NSError?) -> () {
    
        // do something
    
        return {data, response, error in
            // do something else
        }
    }
    

    查看proposal for the removal of the currying syntax 了解有关更改的更多信息。

    【讨论】:

    • 我显然忽略了警告中使用的实际用词,并假设了最坏的情况。您的示例效果很好。谢谢!
    • @MythicsWinter 乐于助人:)
    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 2011-09-20
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    相关资源
    最近更新 更多