Swift: cannot index value of type '[UIViewController]?'

I am trying to figure out how to fix this problem in Swift on Xcode 7 (iOS9), and I also have this error:

Cannot tune value of type '[UIViewController]?' with an index of type 'Int'

Any suggestion appreciated. Thanks.

enter image description here

My code is:

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 } 
+6
source share
1 answer

Try:

 let currentViewController = pageViewController.viewControllers![0] 

It would be safer to write:

 if let currentViewController = pageViewController.viewControllers?[0] { // ... and then do everything else in the if-block end 

Another alternative:

 guard let currentViewController = pageViewController.viewControllers?[0] else { return } // ... and then just proceed to use currentViewController here 

This has the advantage that it is safe, but there is no need to put the rest of the function inside the if block.

+8
source

Source: https://habr.com/ru/post/989251/


All Articles