0

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];
        });

        }];
Community
  • 1
  • 1
shoujo_sm
  • 3,173
  • 4
  • 37
  • 60

1 Answers1

2

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].

Marcos Crispino
  • 8,018
  • 5
  • 41
  • 59