首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Swift闭包:不能用参数列表调用函数

Swift闭包:不能用参数列表调用函数
EN

Stack Overflow用户
提问于 2015-07-26 12:12:51
回答 1查看 749关注 0票数 2

我正在使用闭包编写一个Swift函数。应该编译的代码示例如下所示,

代码语言:javascript
运行
复制
import Foundation

typealias PKSynchronizeProgressBlock = (Double) -> Void
typealias PKSynchronizeCompletionBlock = (Bool, NSError?) -> Void

class X {

func synchronizeAppDataWithProgress(
    progress: PKSynchronizeProgressBlock?, 
    completion: PKSynchronizeCompletionBlock?) {
        dispatch_async(dispatch_get_main_queue(), {

                // Do a lot of downloading, and during the process
                // {
                // If progress is updated
                if (progress != nil) {
                    progress!(Double(0))
                }
                //
                // If something goes wrong
                if (completion != nil) {
                    completion!(false, nil)
                }
                // }
                dispatch_async(dispatch_get_main_queue(), {
                    if (completion != nil) {
                        completion!(true, nil)
                    }
                })
        })
}


func foo() {
    self.synchronizeAppDataWithProgress({ (progress: Double) -> Void in
        self.launchProgressBar.progress = progress
    }, completion: { (success: Bool, error: NSError?) -> Void in
        if success {
            self.launchProgressBar.progress = 1.0
        }
        else {
            print("Failed to synchronize app data with error %@", error!)
        }
    })
}

}

但是,此代码不编译。Xcode说

不能使用参数列表调用'synchronizeAppDataWithProgress‘(进度:(双) ->无效,完成:(Bool,NSError?) -> Void)’

我该怎么办?我的密码里有什么愚蠢的错误吗?

更新:

多亏了马里奥·扎农。我修正了上面代码中的前两个错误。这就是:(1)我在函数调用中插入了一个冗余的progress:。我已经把它去掉了。(2)在主线程之外的线程中更新UI。

但是,如果我不注释掉foo()中的以下一行,则代码仍然不能工作,

代码语言:javascript
运行
复制
self.launchProgressBar.progress = progress

你知道为什么吗?

EN

回答 1

Stack Overflow用户

发布于 2015-11-12 21:27:23

Xcode有时在闭包中列出参数的方式上很挑剔。我发现最好还是把这种类型推断出来。还要确保使用捕获列表来避免闭包中的强引用周期。

使用阿拉莫火依赖项,我重写了上面的代码,它编译了。

代码语言:javascript
运行
复制
import Alamofire

typealias ProgressBlock = (Double) -> Void
typealias CompletionBlock = (Bool, ErrorType?) -> Void

class ExampleDataSource {
    func fetchData(progress: ProgressBlock?, completion: CompletionBlock?) {
        // Here we use the Alamofire Dependency for progress reporting simplicity.
        Alamofire.request(.GET, "https://www.myexampledomain.com")
            .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
                // bytesRead, totalBytesRead, and totalBytesExpectedToRead are Int64
                // so we must perform unit conversion
                let progressPercentage = Double(totalBytesRead) / Double(totalBytesExpectedToRead)
                // here we optionally call the ProgressBlock 'progress' and pass it the progressPercentage
                progress?(progressPercentage)
            }
            .response { request, response, data, error in
                // here we usually parse the data, but for simplicity we'll
                // simply check to see if it exists.
                let completionFlag = (data != nil)
                // note that NSError? is interchangable with ErrorType?
                completion?(completionFlag, error)
        }
    }
    func performTasks() {
        // first we'll set up our closures...
        let progressBlock: ProgressBlock = { progress in
            // here we update the UI or whatever 
            // the nice thing about the Alamofire dependency is
            // that it's thread-safe :]
        }
        let completionBlock: CompletionBlock = { success, error in
            // here we do whatever we need to do when the
            // network operation finishes, or handle the 
            // errors appropriately
        }
        // then we'll pass them into our fetchData method
        fetchData(progressBlock, completion: completionBlock)
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31636821

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档