5

I'm trying to get the selected index of the tabbarController.

let application = UIApplication.sharedApplication().delegate as AppDelegate
let tabbarController = application.tabBarController as UITabBarController
let selectedIndex = tabBarController.selectedIndex

I'm getting this error: 'UITabBarController?' does not have a member named 'selectedIndex'

Am I missing something?

return true
  • 7,839
  • 2
  • 19
  • 35
Maystro
  • 2,907
  • 8
  • 36
  • 71

2 Answers2

14

application.tabBarController is an optional, this means it can be nil. If you are sure it will never be nil, do this:

var selectedIndex = tabBarController!.selectedIndex
return true
  • 7,839
  • 2
  • 19
  • 35
4

you should try this:

let application = UIApplication.shared.delegate as! AppDelegate
let tabbarController = application.window?.rootViewController as! UITabBarController
let selectedIndex = tabbarController.selectedIndex
nabu
  • 552
  • 5
  • 16