icestorm0806
icestorm0806

Reputation: 711

Do you need a separate .swift file for each view controller in an app?

This is a very beginner question as I am new to the swift language and working on my first app. I have been working in the default View Controller, which allows me to create outlets in the ViewController.swift file. but when I create a new view controller I am unable to attach outlets to the ViewController.swift file. so do I have to add a new .swift file for each view controller I add to the project?

Upvotes: 6

Views: 4916

Answers (2)

backslash-f
backslash-f

Reputation: 8193

Definitely. Best practice is a separate file for each View Controller and other major classes.

Refer to this awesome free course from Stanford for a very nice introduction on MVC (Model-View-Controller).

Upvotes: 2

Chajmz
Chajmz

Reputation: 749

You have to assign to your new controller in the storyboard a class (inside a .swift file), but you can have multiple controllers with the same class, just add a class to your controller here :

enter image description here

Example :

If you have a Test.swift like this :

//Test.swift
class viewController1: UIViewController {
}

class viewController2: UIViewController {
}

You could assign viewController1 or viewController2 inside your storyboard to your ViewController, however you should always have a single subclass of UIViewController inside your .swift file.

Upvotes: 2

Related Questions