2

I have this objective-c method that i'm trying to re-write to swift.

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    int index = [navigationController.viewControllers indexOfObject:viewController];
    self.pageControl.currentPage = index;
}

I'm having difficulties writing this line in swift:

int index = [navigationController.viewControllers indexOfObject:viewController];

How do i access the IndexOfObject?

Lord Vermillion
  • 5,264
  • 20
  • 69
  • 109
  • 1
    In Swift 2.0 you could you the indexOf method, see http://stackoverflow.com/a/24069331/3617012 – iOSX Sep 15 '15 at 09:11
  • How can i check what Swift version i am using? – Lord Vermillion Sep 15 '15 at 09:15
  • 1
    If you are using Xcode 7 (not yet released officially), then you have Swift 2.0 at your fingertips. Xcode 6.4 supports Swift 1.2, and you would use the `find` function instead of `indexOf`. How to use it is also explained in the answer that I've linked to in my previous comment. – iOSX Sep 15 '15 at 09:23

4 Answers4

5

In Swift 1.2 (Xcode 6.x)

let index = find(navigationController.viewControllers, viewController)!

In Swift 2.0 (Xcode 7.x)

let arrayOfVCs = navigationController.viewControllers as Array
let index = arrayOfVCs.indexOf(viewController)
Nishant
  • 12,529
  • 9
  • 59
  • 94
1

In Swift 4, for TabBarController, to get index of selected view controller:

let index = tabBarController.viewControllers?.index(of: viewController)
Pang
  • 9,564
  • 146
  • 81
  • 122
Ashim Dahal
  • 1,097
  • 13
  • 15
1

In Swift 5 index(of element: Element) is deprecated .. so use

let index = navigationController?.viewControllers.firstIndex(of: yourController)
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49
0

In Swift 3.0 (Xcode 8.x)

let index = navigationController.viewControllers?.index(of: viewController)