简体   繁体   English

迅速逃脱关闭

[英]escaping closure in swift

I have read a lot of material on stack overflow and I just cannot figure this one out: 我已经阅读了很多有关堆栈溢出的内容,但我无法弄清楚这一点:

I have been this line of code from an online source for hours and I just don't know why the closure that is being passed into a function is escaping, here is the code: 我从网上获得了这行代码已有好几个小时了,我只是不知道为什么要传递给函数的闭包转义,这是代码:

func composeFunction(functionA: @escaping (Int) -> String, functionB:  @escaping (String) -> String) -> ((Int) -> String) { 

    return {

        number in 

        functionB(functionA(number))
    }
}

From apple's documentation, closures are escaping when: 1) Asynchronous operation that runs on a background thread 2) The closure is interactive with properties outside of it's scope (using self ) 从Apple的文档中,闭包在以下情况下转义:1)在后台线程上运行的异步操作2)闭包与其作用域之外的属性进行交互(使用self

But I don't see those are happening, many help will be appreciated! 但我看不到这些正在发生,许多帮助将不胜感激!

Thanks! 谢谢!

your func composeFunction returns a ((Int) -> (String)) and that is exactly a closure. 您的func composeFunction返回一个((Int) -> (String))而这恰好是一个闭包。 Of course now this means functionA and functionB are going to be escaping because we don't know when and where this closure will be called. 当然,现在这意味着functionA和functionB将转义,因为我们不知道何时以及在何处调用此闭包。 Moreover, this is because it needs to know if it should keep the reference to the objects passed in / being manipulated. 此外,这是因为它需要知道是否应保留对传入/正在操纵的对象的引用。 For example, if all your closure parameters had (() -> Void) instead and you also returned (() -> Void) then it would not need to be escaping. 例如,如果您所有的关闭参数都改为(() -> Void)并且您还返回了(() -> Void)则不需要转义。

{
    number in 
    functionB(functionA(number))
}

is a closure. 是一个关闭。 Returning it causes both functionB and functionA to escape, because it becomes unknown at what point this closure will be called or deallocated. 返回它会导致functionBfunctionA都转义,因为在什么时候调用此闭包或将其释放都变得未知。

This is different from just return functionB(functionA(number)) , which causes the immediate invocation of both of those functions, and causes them to never escape the composeFunction context. 这不同于仅return functionB(functionA(number)) ,后者导致立即调用这两个函数,并使它们永不逃避composeFunction上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM