NS_VALID_UNTIL_END_OF_SCOPE 的 Swift 等价物是什么?

What is the Swift equivalency of NS_VALID_UNTIL_END_OF_SCOPE?

场景:

我正在将 Apple 提供的 Objective-C 示例代码翻译成 Swift 3.0.1.

我遇到了一些代码,需要在调用 preventViewController 之前阻止 presentationController 被释放。因此使用 NS_VALID_UNTIL_END_OF_SCOPE(见下图)。

使用 Swift 的最佳替代方案是什么?
...没有它...我得到的只是 transitioningDelegate 值在不久之后访问时的 nil。

您可以尝试使用 withExtendedLifetime(_:_:):

override func perform() {
    let sourceViewController = self.destination
    let destinationViewController = self.destination

    // For presentations which will use a custom presentation controller,
    // it is possible for that presentation controller to also be the
    // transitioningDelegate.
    //
    // transitioningDelegate does not hold a strong reference to its
    // destination object.  To prevent presentationController from being
    // released prior to calling -presentViewController:animated:completion:
    // the NS_VALID_UNTIL_END_OF_SCOPE attribute is appended to the declaration.

    let presentationController = AAPLAdaptivePresentationController(presentedViewController: destinationViewController, presenting: sourceViewController)

    withExtendedLifetime(presentationController) {

        destinationViewController.transitioningDelegate = presentationController

        self.source.present(destinationViewController, animated: true, completion: nil)
    }
}

否则,这将适用于图中所示的情况:

override func perform() {
    let sourceViewController = self.destination
    let destinationViewController = self.destination

    // For presentations which will use a custom presentation controller,
    // it is possible for that presentation controller to also be the
    // transitioningDelegate.
    //
    // transitioningDelegate does not hold a strong reference to its
    // destination object.  To prevent presentationController from being
    // released prior to calling -presentViewController:animated:completion:
    // the NS_VALID_UNTIL_END_OF_SCOPE attribute is appended to the declaration.

    let presentationController = AAPLAdaptivePresentationController(presentedViewController: destinationViewController, presenting: sourceViewController)

    destinationViewController.transitioningDelegate = presentationController

    self.source.present(destinationViewController, animated: true, completion: {
        let _ = presentationController  //<- having a strong reference in the completion handler
    })
}