General questions regarding Swift

Discussion in 'iOS Programming' started by mildocjr, Apr 19, 2016.

  1. mildocjr macrumors 65816

    I came from C# development and even though I've been spending the past few months looking into iOS development and know enough to keep me busy for a while, all I've ever seen is people putting code directly into the ViewController leading to a fat controller. My coding experience has led me to break everything out into separate files and have helper classes to hold commonly used methods and running most of the heavy lifting code (such as creating a deck of cards or grabbing user input and performing complex calculations).

    I was taught that methods should not have any more than 6 lines of code in them, classes should not be larger than the height of your screen, and of course repeated code should be a method. Now classes I've created I have no problems with generally keeping it on the height of my screen, but the GameScene class or ViewController class end up being pretty large, and Apple tends to place a lot of code directly in these such as didMoveToView and viewDidLoad in their templates.

    I'm just curious if there was a best practice for all of this. Yes I understand the MVC structure, but the structure seems to be night and day between ASP.NET and Swift. Is this contributed to performance issues with multiple helper classes and the LLVM compiler?
  2. 1458279 Suspended


    May 1, 2010
    There's at least two issues here, performance and coding style. As far as performance goes, my guess is that the compiler will sort things out. IMO, it's more about readability than anything else.

    I don't know how the system loads code, if a module gets loaded differently or does the runtime just see a bunch of structs and methods.

    I've notice that the MVC is explained in graphics, but I haven't seen many large example projects that really split things out in a logical manner. It's easy to just dump things into one spot rather than go thru messages and make classes.

    It would be helpful if someone actually posted a larger project that showed what code should go where, although I think most simply take short cuts.
  3. mildocjr, Apr 19, 2016
    Last edited: Apr 19, 2016

    mildocjr thread starter macrumors 65816

    I've seen it split out before but in C#, your view is essentially your webpage or Form page (storyboard in iOS) that's easy enough. The model is your heavy lifting code or the stuff that contains all the business logic ( such as x = 1; x =+ 1; ) and the controller basically tells the model to do it's thing when a button is pressed from the view. At least that's how it was explained to me. When you have a data layer it becomes another part of that, so if you have a file or a database the data will be read and written by a Model. How and when that Model is invoked is dependent on whether it is called at the application start or called when an action is performed on the View.

    So breaking it down into layman's terms say you walk into a bar, you ask a server for a drink and that person goes to the bartender who mixes everything and hands it back to the server who then brings it to your table.

    You are the View, the server is Controller, and the bartender is the Model. The data would be the ingredients for the drink, a 8 oz glass, and whatever garnishment you want on it. (This is probably the explanation for everyone else).

    I've seen some C# projects that use this but you end up having 3 classes with Entity Framework that are just used for converting the data into something the model can understand. One being the actual persistence layer class that contains calls to the data from it's storage, one being an Interface for the data layer class to convert to a model class, and then a 3rd just to represent the data as a model class so the domain layer can act on it, by the time it's been manipulated, the controller grabs the resulting data and presents it to the view controller.

    I agree about putting everything in one file but I'm just trying to ensure that my apps are optimized as best as possible.

    I've answered one of my questions, from a few more searches, and breaking it out into other files does help app performance, but I'm wondering about best practices. Even just a link would do fine.
  4. 1458279 Suspended


    May 1, 2010
    "Back in the day" we used to just say "keep your data separate", maybe that shows how long I've been doing this stuff :D

    I think part of the problem that people have is that the examples given don't dig into the code very deeply.

    Off-hand, the only good example I can think of was Stanford's iOS programming CS193P classes. IIRC, he gave some good examples of using MVC and showed the code to do it. They should still be up in the iTunesU.

    Part of the problem is the OO part of programming. Knowing when to make classes and how they message each other, what should be private and what should be private.

    IMO, a good example would be a larger project that shows all the database classes and all the interface classes and why they are designed the way they were. This doesn't seem to be taught much.

    Most of the discussion seems to be around "how do I code ______" rather than how do I design my classes for this.

    Look at the questions here and other forums, rarely do you see any questions about the best way to layout classes.
    --- Post Merged, Apr 19, 2016 ---
    Maybe this link will give some insight:

    There's another model called MVVC that addresses issues of bloat in the MVC model.

    What I try and do is separate out specific business logic from the rest of the program so that my code will work with different business models. Back in the day, they wanted to put business rules on a server so that the front end didn't deal with business logic. I think of it as making code more reusable.

    Example of a database example would compare some of the programs you see where they have "name, address, phone" hard coded into a file vs reading the database, finding what the fields are and displaying the fields based on a set of rules.
  5. mildocjr thread starter macrumors 65816

    I agree 100% with that and awesome post on your experience.

    I feel as though with devices always changing I should be able to change my view controller without changing the business logic that much and my data never changes, or if I want to load my data from a different database I'm not re-coding everything, just the models that access the data. With Swift 3 right around the corner if I don't plan for separation I'm going to end up having to edit everything rather than just my business (domain) logic. I haven't yet looked at the link you posted but I think this discussion is proving more useful in showing that iOS doesn't have an "Apple approved" standard for design patterns.
  6. xStep macrumors 68000

    Jan 28, 2003
    Less lost in L.A.
    A good start is separation of responsibility and duties, and many design patterns that are common in all development. Coders are often interested in jumping into coding rather than planning it out before hand. Just as UI designers design the interface, coders should be putting work into designing their code before writing it.

    This guy has a few opinions on bloated view controllers. Another one that discusses separation of data access is a good video to watch; Exploring MVC-N in Swift.

    Every time I hear something as restrictive as 6 lines of code to a method/function and limit a class to screen height, I just laugh. I picture a mess of a million little files and functions that I'd have to keep track of and flip back and forth between to understand even minimal code. To me, that's as asinine as bloated code. Find the balance that works for you, and possibly a team.
  7. 1458279 Suspended


    May 1, 2010
    Back a few years ago there was much talk about the "gold rush" being over. There was a time when a simple "flashlight" app was worth big money. This drew in many "developers" searching for gold.

    As the sun began to set on the gold rush, the number of "developers" fighting over the same ad dollar increased and we had the great race to the bottom.

    Spitting out "flavor of the month" apps doesn't leave much time for thinking about design.

    I was an independent business software developer for many years long ago and learned the hard way about how software is developed.

    Apple doesn't look at coding style, so there's less reason to care, more so if it's a "hit and quit" app that is only there to make a quick buck.
    --- Post Merged, Apr 19, 2016 ---
    I'm glad someone else said what I was thinking :D
    Same could be said for routines inside the code. I'm working on a universal database system that'll read different sources, SQLite, web services, etc...

    There's a balance between making a bunch of small methods and bringing things together in a way that's easy to work with.

    Hunting thru files trying to track down code isn't the funnest thing to do.

    One of the most useful routines I ever wrote was a generic database browser. It worked on an AS/400 down to a PC, all with the same code and replaceable data drivers.

    IMO we have too many people focused on "make the app work" and not thinking long term about how reusable the code will be.
  8. mildocjr thread starter macrumors 65816

    That's my point in this thread, Code reusability, ease of maintenance, and utilizing design patterns that keep the app working smoothly even when it's 100+ MB in size. I get it that devices now provide 2 GB of RAM but just because it is there doesn't mean my app should be entitled to all of it, as I work on throw away apps that I do for practice I'm constantly thinking about how many variables I have in memory at one time. I'm a big fan of having ad hoc variables, and I cringe when I delve into a more advance tutorial where seemingly all the variables used are instantiated for the lifetime of the application, not just the portion where it is actually needed.

    I did find a playground on design patterns in swift which I'm currently going through, so far it seems to be worthwhile. Here's the link in case anyone else is interested.
  9. 1458279 Suspended


    May 1, 2010
    That's actually not far off of what I did with business apps. I'd write generic routines that I could reuse on different apps.

    The beauty of it was after a while when you need something done, you find that you already have a huge head start.

    In fact, that's really to overlooked part of the the tech race. It's not just about getting things out there, it's about being able to compete with someone that has a huge selection of routines that they can use for the next thing. It's the difference between someone being able to put out one app or put out many different apps.

    I just ran into one example this last weekend. I wanted the navbar label to have a gesture recognizer on it. I searched many solution and didn't find any that really worked well.

    The example was a Big5 sporting goods app that had a turning selector at the center of the navbar. Another example is a search inside the navbar.

    The best approach would probably have been to use categories to add the functionality to the navbar, but I went with a clear view over the center and grabbed the taps from that.

    I was surprised that nobody had designed one properly.

    I'll check out that link, too bad it's not for ObjC, I'm passing on Swift for a little while longer.
  10. xStep macrumors 68000

    Jan 28, 2003
    Less lost in L.A.
    I aware of guy who still makes good money on a flashlight app.

    If you're not aware of it, look into Data Federator by Business Objects. That is a universal data access tool designed to help with BI report tools. It appears as a SQL database to clients and the varied data sources (flat files, other DBs, etc.) appear as database views. I evaluated it several years ago. It's a cool idea but in the scenario I was asked to look at, it was far too slow. When I was looking at it, I had dug up original papers on the design ideas behind it, so that maybe helpful to you.
    --- Post Merged, Apr 19, 2016 ---

    Looks like we come from the same time frame. :)
    --- Post Merged, Apr 19, 2016 ---
    Found another take on handling the bloat in view controllers; The MVC-Trap. That same writer also has
    The Most Common Mistakes in iOS Development which also has a link on handling table views well.
  11. dantastic macrumors 6502a


    Jan 21, 2011
    For some reason I do agree that much of the iOS/Mac community is struggling a bit with code hygiene. You often come across sample code where everything is just dumped into a viewcontroller. This is clearly not right. But there has never been much of a movement to correct it or raise awareness either.
    There is no Uncle Bob for iOS.

    Part of the problem is how approachable the iOS platform is. A huge amount of tutorials available online to help people start programming. And as much as it's great people are getting involved. I think people learning programming from youtube videos will likely struggle to properly design an OO application. Everything ends up getting dumped into a viewcontroller. And in time, that become the 'done way'.
  12. AxoNeuron, Apr 20, 2016
    Last edited: Apr 20, 2016

    AxoNeuron macrumors 65816


    Apr 22, 2012
    The Left Coast
    My opinion is this: do what works, don't follow any guidelines as a religion that can never be broken. Dogma is bad.

    There is this notion that view controllers should be small enough to crush under your boot, and I would agree with this...most of the time. But there are exceptions. If there is a section of code that you know you literally will never use again anywhere throughout the app, why not stick it in the only VC that will actually use it? As long as it's not repetitive and doesn't end up getting duplicated, then put it wherever it's most useful.

    Some programmers go from having a good habit (modularity) and then take them too far. Modularity is mostly a good principle but for some things it actually increases the complexity of the app without any benefit. So yes, I would say that you should try to put as much code as you can in modular classes and such, but don't overdo it.

    Your experience in ASP.NET is pretty much exactly the same as what we do in commercial Swift projects, separate classes for data models, helper classes, views, etc. Everything in their own container. In my projects for example, even the cells in a UITableView will always have their own XIB interface file and their own class. But for example, say there's a single view controller that will be the only view controller in the app to process text in some special way. Assuming it's only an extra line of code or two, I don't see a problem with putting that code in the view controller code.
  13. 1458279 Suspended


    May 1, 2010
    I'm having a bit of trouble thinking someone is STILL making money off a flashlight app, but hey, someone made a mint off a Flappy Bird :D

    That DF BI tool sounds interesting, I'm not too surprised that it was slow. I wrote one myself many years ago and it was fast, but you selected the data driver at the start and it used RDD (Replaceable Data Drivers).

    As far as OO goes, I started out with function based programming and OO was seen as a new thing back then. IMO, OO was a solution to bloated, hard to read programs.

    It's probably one of the most mis-used models we have. I see it as a set of rules that the compiler enforces for things like Private, Public, etc... It's designed so that the program designer can make up a rule for a method, iVar, etc that everyone is supposed to follow. The problem is that it's often viewed as a set of rules that you work around.

    I think of it as a traffic system where you add lights and stop signs. It only works well if you actually take the time to design the system properly. This requires that you understand the rules and create a system of rules that actually makes sense.

    Otherwise, it only really serves to make it harder for people to understand what you're doing.

    Just like any tool, you have to take the time to learn how it should be used.

    It's interesting that Swift offers function based programming. I didn't think I'd ever see function based programming in a new language. I don't know if it's faster, but I know it's easier to learn and maybe people will adopt it because of that.
  14. mildocjr thread starter macrumors 65816

    It's not too bad, the closures are probably the weirdest part for me, as I'm coming from very little Obj-C knowledge. Swift is a much cleaner language and that's probably why I've taken to it more easily.

    I'm still figuring out blocks in closures because Apple suggests the block resides in the parameters and some of the tutorials show the block coming after the parameters such as the following code:
    ac.addAction(UIAlertAction(title: "OK", style: .Default) { [unowned self, ac] _ in
            let newName = ac.textFields![0]
   = newName.text!
    I haven't had much trouble getting through Swift and I've already made a few personal projects that I use at home, the only thing I wish XCode would do is create methods once you type them out. So if I'm making a dice game and I know I need
    var movePlayer: Int = Game.rollDice(dice1, secondDie: dice2)
    swift would generate a roll method accepting two Dice objects in the Game class.
    func rollDice(firstDie: Dice, secondDie: Dice) -> Int {
       // code...
  15. Mascots macrumors 68000


    Sep 5, 2009
    Honestly, I blame Apple because they offer little guidance on things like this. Probably like you said, because of the openness and approachability aspect, but come on', even Wordpress has coding standards and offers a lot more guidance for maintaining code.

    I think there has been large moves away from the horrid VC dumping grounds, but there's more resistance to that than just has Swift in general which prevents those ideas from trickling away from advanced concepts, and thus being less readily available for newer audience eyes. And the resistance seems to be mostly the pointless I don't want to have to change because everything works for me the way I've got it mentality or you can't tell me to code in a box, so it's not applicable which is simply not-the-point.

    Following strict guidelines will make your life a nightmare, but exploring additional methods will never hurt. I could stand on my soapbox about how to approach each scenario, but as others have rightfully pointed out, each mold is different. However, I'm going to point your towards MVVM format with iOS, a format that is very successful and one that I personally live by, and one that there is much documentation from the community on. More-or-less, it's a tuning to MVC, in my opinion, better suits iOS development in situations that outweigh simple actions.
  16. mildocjr thread starter macrumors 65816

    I'm not saying strict guidelines, I'm saying, this is what works best in relation to app performance and stability. Of course I could take a .NET application and give it one hefty Form class dropping in all my classes variables and methods in that one file, but it doesn't mean that the app will like it at runtime.

    There will be the one offs, but it would be nice if Apple stopped being shy and said "Hey devs, just want to let you know that out of what we tried, this seems to work the best."

    The playground is a nice tool to figure code out to make something work, but at the same time it enables people to continue the bad habit of having all your code in one file.
  17. firewood macrumors 604

    Jul 29, 2003
    Silicon Valley
    A fat view controller is a bad habit that comes from doing incremental development using Apple's app templates. That may be OK for rapid prototyping (fail fast). But once the code looks useful, any separable groups of state plus logic should be split off for better maintainability.

    However, I hate tiny methods and classes, as it scatters longer complex logic into too many places to read and understand linearly and quickly. Not all problems and algorithms are optimally solved by subfactoring into teeny pieces. YMMV.
  18. Mascots macrumors 68000


    Sep 5, 2009
    Oh no, I wasn't suggest, just agreeing with everyone else that looking at existing patterns and following the routines lightly can help drastically.

    I would suggest peaking at some of the public bigger names in Swift development if you need a little confidence of guidance. And also take a look through the history of sites like Little Bites of Cocoa and iOS Dev Weekly. But it sounds like you're doing okay - so go with it.

    I wouldn't take Apple's example code to heart, basically.
  19. AdonisSMU macrumors 603

    Oct 23, 2010
    If you type command + 3 and you can find the thing that you are looking for.
  20. xStep macrumors 68000

    Jan 28, 2003
    Less lost in L.A.
    That is just a way to jump around, and given the possibility of multiple and false hits, could just add to the confusion. Even if your first result is correct, now you've just made a jump which you have to return from. I like to minimize my bouncing around.

    This part of the discussion reminds me of having to go through IBM manuals when I was in college. You'd look up something in one manual (Cobol, Assembler, JCL) that would refer to one or two other manuals. These were big heavy volumes of information. Often enough, when you found the reference in the second manual, it would refer you to some place else. It's nice to have quick online references. Now when you reach that second forward reference, the answer is a click/tap away. :)
  21. AdonisSMU macrumors 603

    Oct 23, 2010
    Yeah I thought about that after I posted it. :D
  22. 1458279 Suspended


    May 1, 2010
    Isn't there a way to make xcode generate the method? IIRC it was something like define the methods, then ignore the 'func' part and start typing the rest of the method name and it makes the method for you? I've been doing so many things, I can't remember all of it :D

    Are you talking about methods that you created or calling methods that have already been created?

    As far as blocks go, someone posted a very complex block in Swift and it was pretty hard to read. ObjC blocks seem pretty straight forward, but that's probably because I'm used to them now.

    Have you seen Simon Ng's book "Intermediate iOS 9 programming with Swift" AppCoda? I haven't gone thru it yet, but it seems to be one of the rare books that aren't beginner books.

    I'm sick of beginner books for mobile development. Someone should pass a law against any more beginner books.
    --- Post Merged, Apr 20, 2016 ---
    TBH, it's not just Apple. Apple didn't do much for forcing good programming, but at the same time, you have "everyone and their brother" becoming an "app developer".

    Computer programming is a science, it's not a "just tell me what to cut and paste to make it work"

    So many people overlook the science of computer programming and just have the mind set "you're a coder, just code the thing".

    One thing that might have saved Apple from having too many CRapps (if that can be done) is that ObjC wasn't as popular as Java was at the birth of mobile.

    Android probably had an upper hand in that it had a more popular language than Apple did at the start of the app gold rush.

    I remember Apple years ago talking about how important it was that the app look good. They had a WWDC where the leather look of a "to do" app was talked about and how they went on about the page turning and how it looked so realistic.
    Not much (if anything) about actually coding style.
  23. mildocjr thread starter macrumors 65816

    I was referring to creating a call to a method that has not yet been created, and allowing the method that I plan to create, generate from the method call. I do like how the method generates when it's called though, saves my fingers with those long method names.

    I just get confused by the {[unowned self, ac] _ in ... //code here} part. I get it that I'm not wanting to own the controller/handler/whateverYouWantToCallIt and pass in the ac variable for the code, but I have a hard time understanding when and when not to use unowned <insert object>. Seems all the code I've written even for personal use seemed to dodge this bullet for now, but after seeing them used I like the functionality they provide.

    I've followed AppCoda since it was in it's infancy but I started a new job with COBOL programming and had to take a break from all of it. It's not a straight forward site like it used to be and most of it's tutorials for getting started are referring to iOS 6 or 7. Not really applicable since iOS 9 introduced swift 2.2 and pretty much did away with all of it.

    I'm right there with you, Swift has been around long enough to where someone shouldn't have to introduce the basics, if anything start making a beginner's book on what's changed based on the hints in Xcode regarding Swift 3.0 and how to prepare for those changes. (such as the removal of i++, c-style for loops, etc...)
  24. 1458279 Suspended


    May 1, 2010
    I went down the road of ObjC so I don't know if Xcode works exactly the same with Swift, but if you define the method first, Xcode should do the rest for you.

    The same holds true for types.

    The way it works is this: (someone jump in and correct me where I'm wrong)
    1. define the method
    2. setup the #includes, #includes, @Property, etc...
    3. program the implementation

    Once these are done, xcode should look things up and finish the code for you.

    I noticed in the Stanford iOS videos that he didn't do things this way, he would be in code and type out the working code, then go back and setup the #defines and other stuff.

    The problem with doing it the reverse way is that you lose the advantage of the editor correcting your typo mistakes.

    Give it at try, setup all the method defines 1st.

    In Swift, (IIRC) you skip the "func" and start typing the other part of the function and Xcode fills in the rest for you.
  25. MarkCollette macrumors 68000


    Mar 6, 2003
    Toronto, Canada
    unowned is for when that reference will continue to exist through the times that your closure can get called. I've found that in most cases, the user can just navigate back out, and so that reference can't be guaranteed, unless for example viewWillDisappear cleans it up, so weak is generally more appropriate.

Share This Page