如何实现与Swift中的Strongify相同的行为? [英] How to achieve same behavior as with strongify in Swift?

查看:64
本文介绍了如何实现与Swift中的Strongify相同的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自我弱的闭包,我需要确保自我在闭包执行期间得以保留,并在执行完成后由闭包释放.以前是由@strongify完成的.在Swift中还有其他方法吗?

I have a closure with a weak self, I need to ensure that self will be retained during execution of closure, and released by closure after execution is done. Previously it was done by @strongify. Is there any other ways to do so in Swift?

推荐答案

在其他答案可行的同时,另一种选择是使用反引号.这样做无需定义strongSelf,并允许使用self而不用解开可选的self.

While the other answers work, another option is to use backticks. Doing so does away with having to define strongSelf and allows using self without having to unwrap optional self.

let c: () -> Void = {
    [weak self] in
    guard let `self` = self else { 
        throw NSError(domain: "self was destroyed", code: 1, userInfo: nil) 
    }
    self.doSomethingNonOptionalSelf()  
}

这篇关于如何实现与Swift中的Strongify相同的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆