Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Cannot subscript a value of type '[UIViewController]?'

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

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

Any suggestion appreciated. Thanks.

enter image description here

My code:

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
}
like image 767
hightech Avatar asked Jun 16 '15 22:06

hightech


1 Answers

Try:

let currentViewController = pageViewController.viewControllers![0]

It would be safer, though, 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's safe but there's no need to put the remainder of the function inside an if block.

like image 72
matt Avatar answered Sep 23 '22 04:09

matt