Evan Evan - 22 days ago 7
Swift Question

iOS & Swift: ViewController class is defined, but when is it created as an object?

Learning Swift as my first new language in many years, I've come across something I'm curious about using Xcode and creating a new iOS project using the single view template.

In the default ViewController.swift file, UIkit is imported, and then the class ViewController is defined, inheriting from UIViewController. But I can't seem to find out where or how this class is ever created or initialized as an object.

Default ViewController.swift example

If I define my own class, or even want to create another view controller, I must first initialize it as an object somewhere in order to use it. So where is this default ViewController getting made?

Thanks for any help you can offer for me to try to conceptualize this!

Answer Source

Open your "Main.storyboard" file. Make sure View Controller is selected on the left sidebar:

enter image description here

Then on the right sidebar you can see that your ViewController class is in the class field:

enter image description here

So, when your app is loaded, the default storyboard is loaded, and that storyboard is responsible for creating an instance of the ViewController class and set it up for you. To test this out, you could create a new class, say ViewController2 and make it inherit from UIViewController. ViewController2 would then be available in the right sidebar:

enter image description here

And then your ViewController2 code will be used instead of ViewController.