本文介绍了在 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.

推荐答案

考虑这个类:

class A {
    var closure: (() -> Void)?
    func someMethod(closure: @escaping () -> 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.number = 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!

您可能想知道,什么?那么闭包从哪里逃逸到哪里?"

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.

默认情况下,Swift 不允许闭包逃逸.您必须在闭包类型中添加 @escaping 以告诉编译器请允许此闭包转义".如果我们删除 @escaping:

By default, Swift doesn't allow closures to escape. You have to add @escaping to the closure type to tell the compiler "Please allow this closure to escape". If we remove @escaping:

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

并尝试编写self.closure =closure,它不会编译!

and try to write self.closure = closure, it doesn't compile!

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

08-14 06:17