Convert Obj C code to Swift weak self

379 views Asked by At

I am using the code here but I'm having difficulty to convert the

__weak __typeof(self) weakSelf = self;

to Swift. Is there a way for me to convert the following code into Swift? I'm stucked convert to Swift even after reading the material said that [unowned self] or [weak self].

        __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

There are 1 answers

0
Marcos Crispino On BEST ANSWER

In Swift you don't need to declare a weakSelf variable outside the closure.

Just define your completion block as follows:

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

and then use self? inside the block, in case it may be nil.

If self cannot be nil, you may need to use [unowned self] instead of [weak self].