Swift 2:“Bool”不能转换为“BooleanLiteralConvertible”

我在XCode 6创build了一个应用程序。 今天我下载了XCode 7 ,它已经将我的应用程序更新到了Swift 2 。 有很多错误,但现在只有一个我不能解决。 我不知道为什么,但Xcode不喜欢任何Bool选项的animated和显示此错误 –

'Bool'不能转换为'BooleanLiteralConvertible'

(如果你看看这个函数本身,你会看到,它完全采用Bool 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' 

有谁知道,我该怎么解决?

谢谢。

斯威夫特是困惑,给你一个不正确的错误信息。 问题是第一个参数的types是[UIViewController]? ,所以以下应该工作:

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

或者更好的是,声明viewControllers的types是[UIViewController]那么在调用中不需要强制转换:

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

如果可能,尽量避免投射。 Swift 1的声明为- setViewControllers:direction:animated:completion:已经从:

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

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

所以你的演员混淆了Swift 2,因为[AnyObject]types[AnyObject]不匹配[UIViewController]? 。 期待更多的Objective-C API将来被审计。

首先修复viewControllerAtIndex返回一个UIViewController

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

那么就让Swift推断正确的types:

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

这是可读的版本:

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