将Obj C代码转换为Swift弱自我

时间:2015-06-18 17:32:24

标签: objective-c swift uipageviewcontroller weak-references self-reference

我正在使用代码here,但我很难转换

__weak __typeof(self) weakSelf = self;
对斯威夫特来说。有没有办法让我将以下代码转换为Swift?即使在阅读了材料上说[无主的自我]或[弱自我]之后,我仍然被皈依Swift。

        __weak __typeof(self) weakSelf = self;
        UIViewController *controller = [self.gamingPageViewController viewControllerAtIndex:index];
        [self.gamingPageViewController setViewControllers:@[controller]
        direction:(self.gamingPageIndex<index)?UIPageViewControllerNavigationDirectionForward:UIPageViewControllerNavigationDirectionReverse
        animated:NO
        completion:^(BOOL finished) {

        // Method to not mess up view order in pageview            
        UIPageViewController* pvcs = weakSelf.gamingPageViewController;
        if (!pvcs) return;
        dispatch_async(dispatch_get_main_queue(), ^{
        [pvcs setViewControllers:@[controller]
        direction:UIPageViewControllerNavigationDirectionForward
        animated:NO completion:nil];
        });

        }];

1 个答案:

答案 0 :(得分:2)

在Swift中,您不需要在闭包之外声明weakSelf变量。

只需按如下方式定义完成块:

{ [weak self] (finished) -> () in ... }

然后在块中使用self?,以防它可能是nil

如果self不能nil,您可能需要使用[unowned self]代替[weak self]