2015-06-16 20 views
6

Próbuję dowiedzieć się, jak rozwiązać ten problem w Xcode Swift 7 (iOS9) i ja również posiadające ten błąd:Swift: Nie można indeksować wartości typu "[UIViewController]?"

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

Wszelkie sugestie mile widziane. Dzięki.

enter image description here

Mój kod:

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 
} 

Odpowiedz

8

Spróbuj:

let currentViewController = pageViewController.viewControllers![0] 

Byłoby bezpieczniej, chociaż, aby napisać:

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

Inną alternatywą:

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

Ma to tę zaletę, że jest to bezpieczne, ale nie ma potrzeby, aby umieścić pozostałą część funkcji wewnątrz bloku if.

+0

Zauważ, że nie ma już potrzeby odrzucania; Swift 2.0 wie, że jest to tablica UIViewControllers! – matt

+0

Również 'pageViewController.viewControllers? .first' pozwala na uniknięcie wyjątków" indeks poza granicami ". – ozgur

Powiązane problemy