0

I have array of strings

var arr = ["firstViewController", "secondViewController", ....]

For each of it's items I need to instantiate ViewController like

var myVC = self.storyboard?.instantiateViewController(withIdentifier: "firstViewController") as! firstViewController

If i want to instantiate View Controllers from loop I need to make class from string but this code

let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!

Is not working

moonvader
  • 19,761
  • 18
  • 67
  • 116
  • Did you try [this](https://stackoverflow.com/a/32265287/308315) solution posted on a similar StackOverflow question? – erik_m_martens Oct 20 '17 at 09:47
  • 1
    _Why_ do you need this? You could just instantiate the controllers in a loop as `UIViewController`s and then try to downcast when needed... – Alladinian Oct 20 '17 at 10:02

2 Answers2

1

In Swift you cannot cast to a runtime type object. Swift knows the types of all of its variables at its compile time.

Now you have a variable, whose value is some type that the compiler knows nothing about, so the compiler cannot let you do anything with variable for type cast.

Reference:- Link1, Link2

arunjos007
  • 4,105
  • 1
  • 28
  • 43
1

No need to use NSClassFromString(_:) to instantiate a UIViewController from a loop. You were headed in the right direction in your first two lines of code:

let nameArray = ["firstViewController", "secondViewController" /*....*/]
var controllerArray = [UIViewController?]()

for name in nameArray {
    controllerArray.append(self.storyboard?.instantiateViewController(withIdentifier: name))
}
Alan Kantz
  • 365
  • 1
  • 2
  • 11