0

I want to determine if first VC of TabBarController is a SearchVC and if it is, load the second VC on launch. I've created subclass of TabBarController and in viewDidLoad() method I tried the following:

if let first = self.viewControllers?[0] as? SearchVC{
    self.selectedIndex = 1
}else{
    self.selectedIndex = 0
}

And

if self.viewControllers?[0] is SearchVC{
    self.selectedIndex = 1
}else{
    self.selectedIndex = 0
}

The first controller is SearchVC and it returns 0 when it should be 1 EDIT: Also if self.viewControllers?[0].isKind(of: SearchVC()) doesn't work

Ryan
  • 4,799
  • 1
  • 29
  • 56
Adam
  • 1,776
  • 1
  • 17
  • 28
  • please read about === operatot in swift https://developer.apple.com/documentation/swift/1538988 or just follow below link https://stackoverflow.com/questions/42624910/how-to-compare-uiviewcontroller-in-swift-3 – Gagan_iOS Oct 25 '17 at 16:56

2 Answers2

1

I missed the fact that my SearchVC controller is embeeded in UINavigationController. The code below solved my problem:

if let firstNav = self.viewControllers?[0] as? UINavigationController{
            if let first = firstNav.viewControllers.first as? SearchVC{
                self.selectedIndex = 1
            }else{
                self.selectedIndex = 0
            }
        }

Thanks for the answers though!

Adam
  • 1,776
  • 1
  • 17
  • 28
0

This is a great use case for protocols & protocol conformance.

First, you can create a protocol such as this:

protocol TabBarInitial { }

No variables or functions should be necessary for this.

Next, have your SearchVC conform to it:

class SearchVC: TabBarInitial { ... }

And test for protocol conformance while using a ternary to set the value:

selectedIndex = viewControllers.first is TabBarInitial ? 1 : 0
CodeBender
  • 35,668
  • 12
  • 125
  • 132
  • Why should we use `protocol` which doesn't have any `protocol`? In this case just need to check its type. – Ryan Oct 25 '17 at 19:02
  • @Ryan For one, it can be reused throughout the application if need be, otherwise OP would have to keep adding classes to test for. Or the class gets renamed, or OP wants to use a different class in the future. – CodeBender Oct 25 '17 at 19:30