我已经将我的代码更新为Xcode 8.0 beta 6,但我似乎陷入了关于新的非转义关闭默认值的问题.在下面的代码中,Xcode建议在下面代码的第一行@escaping前面添加completion:,但是仍然不会编译并进入圆圈.*
(编辑:事实上,@scaping应该在之后 添加completion:,正如Xcode建议的那样.警报可能仍然显示,但清理和编译将删除它.)*如何重新编写/修复此代码以在更新的Swift 3中工作?我看过新手册,但找不到合适的代码示例.
func doSomething(withParameter parameter: Int, completion: () -> ()) {
// Does something
callSomeOtherFunc(withCompletion: completion)
}
// Calling the method and execute closure
doSomething(withParameter: 2) {
// do things in closure
}
Run Code Online (Sandbox Code Playgroud)
任何帮助非常感谢!
编译器错误Closure use of non-escaping parameter 'completion' may allow it to escape,这是有道理的,因为它将在函数返回后调用.
func sync(completion:(()->())) {
self.remoteConfig.fetch(withExpirationDuration: TimeInterval(expirationDuration)) { (status, error) -> Void in
completion()
}
}
Run Code Online (Sandbox Code Playgroud)
但如果我使闭包可选,那么没有编译错误,为什么呢?函数返回后仍然可以调用闭包.
func sync(completion:(()->())?) {
self.remoteConfig.fetch(withExpirationDuration: TimeInterval(expirationDuration)) { (status, error) -> Void in
completion?()
}
}
Run Code Online (Sandbox Code Playgroud) 在Swift中,转义闭包参数用注释@escaping.Objective-C中是否有任何等价物,以便生成的Swift接口标记为@escaping?
我基本上希望有一个可选的完成处理程序,该处理程序没有传递回的参数。这是我到目前为止所拥有的,但显然是错误的。
func refreshAccountData(type:String, completion: (()->(Void))?){
//Network call is made
Alamofire.request... {
completion?()
//Here is where I want to call the optional completion handler
}
}
Run Code Online (Sandbox Code Playgroud)
我不想在完成块中传递任何参数。我只想知道网络通话何时完成,以便刷新UI。我不想在这里刷新UI,因为我希望它充当刷新数据的通用函数。我希望完成处理程序为可选的原因是,有时刷新完成后,我不需要执行任何操作。
我对@转义的含义也很困惑。当我做这样的事情时,我通常会拥有它,但是任何清晰度都会很棒。我已经在网上做了一些功课,但没有得到很多真正的收获。
我extension Array的形式是:
extension Array
{
private func someFunction(someClosure: (() -> Int)?)
{
// Do Something
}
func someOtherFunction(someOtherClosure: () -> Int)
{
someFunction(someClosure: someOtherClosure)
}
}
Run Code Online (Sandbox Code Playgroud)
但是我收到了错误:Passing non-escaping parameter 'someOtherClosure' to function expecting an @escaping closure.
这两个闭包确实是非转义的(默认情况下),并且显式地添加@noescape以someFunction产生警告,指示这是Swift 3.1中的默认值.
知道我为什么会收到这个错误吗?
我有一个函数,它接受两个参数,最后一个参数是一个回调闭包:
func myAsycTask(name: String, callback: @escaping ()->Void) {
myQueue.async{
self.doTask(name)
callback()
}
}
func doTask(name: String) {...}
Run Code Online (Sandbox Code Playgroud)
我想使第二个回调闭包参数可选.我试图将上面的函数重新定义为:
func myAsycTask(name: String, callback: @escaping ()->Void? = nil) {
myQueue.async{
self.doTask(name)
callback()
}
}
Run Code Online (Sandbox Code Playgroud)
我收到编译器错误:
Nil默认参数值不能转换为'
() ->'
我怎样才能实现我所需要的呢?
我知道如果将它分配给类的属性并且在闭包内部使用类的实例属性,则closure可以创建retain cycles.但
1)闭包没有分配给类属性,而是作为参数传递给单例的类方法?
2)在这种情况下如何管理内存?
在我的控制器(UIViewController)的方法中,我有类似的东西:
MySingleton.classMethod(parameters ..., completion: { () -> Void in
/**
doing stuff here
*/
})
Run Code Online (Sandbox Code Playgroud)