本文介绍了在Swift中转义关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift的新手,当我遇到逃逸的闭包时,我正在阅读手册。我没有得到手册的描述。有人可以向我解释什么逃逸关闭在Swift简单的术语。非常感谢。

I'm new to Swift and I was reading the manual when I came across escaping closures. I didn't get the manual's description at all. Could someone please explain to me what escaping closures are in Swift in simple terms. Thank you so much.

推荐答案

考虑这个类:

class A {
    var closure: (() -> Void)?
    func someMethod(closure: () -> Void) {
        self.closure = closure
    }
}

someMethod 将传递的闭包分配给类中的属性。

someMethod assigns the closure passed in, to a property in the class.

现在来到另一个类:

class B {
    var number = 0
    var a: A = A()
    func anotherMethod() {
        a.someMethod { self.number = 10 }
    }
}

如果我调用 anotherMethod ,闭包 {self .nu​​mber = 10} 将存储在 A 的实例中。因为 self 是在闭包中捕获的,所以 A 的实例也会拥有对它的强引用。

If I call anotherMethod, the closure { self.number = 10 } will be stored in the instance of A. Since self is captured in the closure, the instance of A will also hold a strong reference to it.

这基本上是一个转义闭包的例子!

That's basically an example of an escaped closure!

你可能想知道什么? from,and to?

You are probably wondering, "what? So where did the closure escaped from, and to?"

闭包从方法的范围转移到类的范围。它可以稍后调用,即使在另一个线程!

The closure escapes from the scope of the method, to the scope of the class. And it can be called later, even on another thread! This could cause problems if not handled properly.

为了避免意外逸出闭包并导致保留周期和其他问题,请使用 @noescape attribute:

To avoid accidentally escaping closures and causing retain cycles and other problems, use the @noescape attribute:

class A {
    var closure: (() -> Void)?
    func someMethod(@noescape closure: () -> Void) {
    }
}

现在如果你尝试写 self.closure = closure ,它不会编译!

Now if you try to write self.closure = closure, it doesn't compile!

更新:

在Swift 3中,所有的闭包参数默认都不能转义。您必须添加 @escaping 属性才能使闭包能够从当前范围转义。这为您的代码增加了更多的安全性!

In Swift 3, all closure parameters cannot escape by default. You must add the @escaping attribute in order to make the closure be able to escape from the current scope. This adds a lot more safety to your code!

这篇关于在Swift中转义关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 01:41