Swift 2: "Bool" does not convert to "BooleanLiteralConvertible"

I created an application in XCode 6 . Today I downloaded XCode 7 and upgraded my app to Swift 2 . There were a lot of mistakes, but now there is only one that I cannot solve. I don't know why, but Xcode doesn't like any Bool option for animated and shows this error -

'Bool' does not convert to 'BooleanLiteralConvertible'

(if you look at the function, you will see that it accepts exactly Bool for animated )

 var startVC = self.viewControllerAtIndex(indexImage) as ContentViewController var viewControllers = NSArray(object: startVC) self.pageViewContorller.setViewControllers(viewControllers as [AnyObject], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil) 'Bool' is not convertible to 'BooleanLiteralConvertible' 

Does anyone know how I can solve it?

Thanks.

+6
source share
2 answers

Swift is confused and gives an invalid error message. [UIViewController]? problem that the first parameter is of type [UIViewController]? so the following should work:

 self.pageViewContorller.setViewControllers(viewControllers as? [UIViewController], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil) 

Or even better, declare viewControllers as [UIViewController] , then casting is not required in the call:

 let viewControllers:[UIViewController] = [startVC] self.pageViewContorller.setViewControllers(viewControllers, direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil) 
+12
source

Avoid casting whenever possible. Swift 1 declaration for - setViewControllers:direction:animated:completion: changed from:

 func setViewControllers(_ viewControllers: [AnyObject]!, direction direction: UIPageViewControllerNavigationDirection, animated animated: Bool, completion completion: ((Bool) -> Void)!) 

to

 func setViewControllers(viewControllers: [UIViewController]?, direction: UIPageViewControllerNavigationDirection, animated: Bool, completion: ((Bool) -> Void)?) 

so your throw confuses Swift 2 because the type [AnyObject] of viewControllers does not match [UIViewController]? . Expect more Objective-C APIs to be tested in the future.

First fix viewControllerAtIndex to return a UIViewController :

 func viewControllerAtIndex(index: Int) -> UIViewController { ... } 

then just let Swift output the correct types:

 let startVC = viewControllerAtIndex(indexImage) let viewControllers = [startVC] pageViewController.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: nil) 

which is a readable version:

 let startVC: UIViewController = viewControllerAtIndex(indexImage) let viewControllers: [UIViewController] = Array<UIViewController>(arrayLiteral: startVC) pageViewController.setViewControllers(viewControllers, direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil) 
+1
source

All Articles