0

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?

0

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I knew it was something to do with the unwrap but couldn't put my finger at it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.