11

i used to say in obj-c

[self.tabBarController.viewControllers objectAtIndex:1];

but now in swift no ObjectAtIndex any more

self.tabBarController.viewControllers.ObjectAtIndex

Update

ok i am gonna make it simple lets consider i have tabBarController it contains 2 object [FirstViewController,SecondViewController] and i am trying to make a delegate between the object here is the code to set the delegate

var Svc:SecondViewController = self.tabBarController.viewControllers[1] as SecondViewController!
Svc.delegate = self

when i Run , i got this error 0x1064de80d: movq %r14, %rax and no console error is showing up

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Amr Mohamed
  • 2,290
  • 4
  • 20
  • 39

2 Answers2

22

Your code is OK:

var svc:SecondViewController = self.tabBarController.viewControllers[1] as SecondViewController!
svc.delegate = self

... however you can omit ! mark at the end and :SecondViewController type definition since it can be inferred by the cast:

var svc = self.tabBarController.viewControllers[1] as SecondViewController

The problem appears because you try to cast to the wrong class. Try to print to debug log name of the class of object at [1]; add this before your cast to check the class name:

let vcTypeName = NSStringFromClass(self.tabBarController.viewControllers[1].classForCoder)
println("\(vcTypeName)")

UPDATE:

As we figured out in comments, you should cast received view controller to UINavigationController:

var nc = self.tabBarController.viewControllers[1] as UINavigationController

Later you can examine nc.viewControllers property and see if for instance its topViewController is SecondViewController:

if nc.topViewController is SecondViewController {
    var svc = nc.topViewController as SecondViewController
    // your code goes here
}
Keenle
  • 12,010
  • 3
  • 37
  • 46
  • console print `UINavigationController` and now i should pass the UINavigationController first right ? – Amr Mohamed Aug 19 '14 at 22:00
  • It means that at the 1-st position in your `viewControllers` array you have `UINavigationController` which is obviously not `SecondViewController` class that you use for the cast. That is why you get the error. Do you have your `SecondViewController` class instance wrapped inside navigation view controller? – Keenle Aug 19 '14 at 22:02
  • 1
    yeah i have a UINavigationController before both first and second viewController – Amr Mohamed Aug 19 '14 at 22:05
  • Thanks. Save my day +1. – Tushar Lathiya Mar 30 '21 at 10:35
3

You don't need objectAtIndex in swift, just use the subscript operator:

self.tabBarController.viewControllers[1]
Mike S
  • 41,895
  • 11
  • 89
  • 84