iSee
iSee

Reputation: 604

Calling UITabBarController delegate programmatically in Swift

I have a perfectly working code in Objective-C that is called to change the selected tab programmatically based on certain criteria.

-(void)loadNewView
{
    UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
    [tabBarController setSelectedIndex:2];
    [tabBarController.delegate tabBarController:tabBarController didSelectViewController:[tabBarController.viewControllers objectAtIndex:2]];
}

I am trying to get the equivalent of the same in Swift and below is the code I have tried

func loadNewView() {
    var tabbarController: UITabBarController = self.window?.rootViewController as UITabBarController
    tabbarController.selectedIndex = 2
    var svc = tabbarController.viewControllers[2] as UINavigationController
    tabbarController.delegate?.tabBarController(tabbarController, didSelectViewController:svc)
}

However I am getting the "[AnyObject]? does not have a member named subscript". I know something is wrong with the above Swift code but can anybody help me in understanding the error?

Upvotes: 0

Views: 2885

Answers (1)

Jawwad
Jawwad

Reputation: 1336

Yup, [AnyObject]?, which is an optional array, doesn't have a member named subscript but [AnyObject] does, i.e. you can't use subscript notation on an optional array, so you have to unwrap it first with "!".

Try this:

var svc = tabbarController.viewControllers![2] as UINavigationController

Upvotes: 1

Related Questions