我试图弄清楚如何在
Xcode 7(iOS9)上的
Swift中解决这个问题,我也遇到了这个错误:
Cannot subscript a value of type ‘[UIViewController]?’ with an index of type ‘Int’
任何建议表示赞赏.谢谢.
我的代码:
func indexPositionForCurrentPage(pageViewController: UIPageViewController) -> Int { let currentViewController = pageViewController.viewControllers[0] as UIViewController for (index,page) in pages.enumerate() { if (currentViewController == page) { return index } } return -1 }
解决方法
尝试:
let currentViewController = pageViewController.viewControllers![0]
但是,写一下会更安全:
if let currentViewController = pageViewController.viewControllers?[0] { // ... and then do everything else in the if-block end
另一种选择:
guard let currentViewController = pageViewController.viewControllers?[0] else { return } // ... and then just proceed to use currentViewController here
这样做的好处是它安全,但不需要将函数的其余部分放在if块中.