Search code examples
swiftrefactoringviewcontroller

Swift : Using multiple swift files or not with only one viewController? Keeping it clean


I'm pretty new in programming in swift. Right now I'm halfway through a course and really loving it. Right now I'm a musician and before I started this course, I already had an idea of what app to make. So I started making this Music Play along app and am pretty happy already with how it's coming together. On to my question :

I've been coding all of my functions, variables and outlets into the main ViewController.swift file. It's becoming a pretty long read and I was thinking if it would be better to separate some functions in different swift files. Now as I understand it, different .swift files come into play if you create classes that aren't directly related to each other, but so far all of my code is related to this single ViewController aka the main screen. Disregarding the efficiency that probably could be better in my coding, should I keep on going in this single file, or should I start differentiating some parts of my code and put them in their own swift files?

Alright thanks in advance and also, thank you SO much for all the invaluable information on this website. This is a pretty amazing community. -Patrick


Solution

  • First of all, I structure my code like this: the ViewController is divided into 3 files, in the first there is the declaration and also the override methods and obj-C methods, in the second file I put the delegate, on extension for each delegate and in the first there is a unique extension where I put all the helper methods. If the application contains only one ViewController you can leave all inside the main, but if the app will be a more complicated and structured, it's better you create a second viewController presented by the parent ViewController where you perform all what you need to do.