Swift 2:“布尔值”不可转换为 'BooleanLiteralConvertible'

Swift 2: "Bool' is not convertible to 'BooleanLiteralConvertible'

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

'Bool' is not convertible to 'BooleanLiteralConvertible'

(如果你看一下函数本身,你会发现,animated 正好需要 Bool

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'

有人知道吗,我该如何解决?

谢谢。

Swift 很困惑,给你一个不正确的错误信息。问题是第一个参数是 [UIViewController]? 类型,所以下面应该有效:

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

或者更好的是,将 viewControllers 声明为 [UIViewController] 类型,然后在调用中不需要转换:

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

尽可能避免投射。 Swift 1 declaration for - 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 因为 viewControllers 的类型 [AnyObject][UIViewController]? 不匹配。预计将来会审计更多 Objective-C 个 API。

首先将viewControllerAtIndex修改为return一个UIViewController:

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

然后让Swift推断出正确的类型:

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)