preview mvc

Three Ways to Make Your Swift Code More Readable

The importance of code readability is often underestimated, especially when programming in an environment which emphasizes user interface and user experience. While it’s true that it is extremely important to make a great app, it’s equally important to be able to change it in the future. With unreadable code, it can be much harder to solve bugs, with countless hours of trying to find the correct lines of code and to understand how it works.

Any fool can write code that a computer can understand. Good programmers write code that humans can understand. — Martin Fowler

With that in mind, let’s get started and learn some ways to make your code more readable both for yourself and for others who may need to make changes to it in the future.

1. Use Comments

This may seem like an obvious method of making code more readable, but it’s often overlooked. If you’re writing Swift code, it’s likely that you’re using Xcode as a compiler, and conveniently, it turns out that Xcode is packed with features that help make your code more readable.

Single-Line Comments

The most widely used type of comment is a single-line comment. Lots of us use the two forward slashes in front of a line so that it will be ignored by the compiler, but don’t forget how useful it is for documenting your code!

As a refresher, here’s how to do a traditional single-line comment:

By convention, the comment is above the line that it explains in more detail. Try to use your comments to add explanation or insight into your code, beyond just describing what the line does. For example, the following comment for the code above is not helpful, because it doesn’t add any further explanation beyond what is immediately apparent.

Quick Help Comment

You may have used Command-Click to get more information about a particular variable, class, or method, but did you know that you can add information like this to your own code? You can! To do this, use a special single-line comment syntax as follows: three slashes, followed by a space and a dash. Then add the attribute name (for example, “parameter”) and then finally, type out the word, and then its definition.

Here’s an example of a quick help comment syntax:

When you Command-Click the foobar function anywhere that it’s used, you’ll see its definition shown under parameters.

Block Comments

A less widely used type of comment is a block comment. These comments are typically used to put licensing information and copyright information at the top of the file, but they can also be used if you need write multiple lines explaining your code (though it’s a good rule of thumb that if you need that many words to explain your code, it probably isn’t readable enough).

To make a block comment, start with a forward slash, an asterisk, and then your code. Once you’re ready to end the comment, you can simply place an asterisk and then another forward slash.

Here’s an example of it:

Block Comments for Quick Help Documentation

Getting back to the quick help documentation, block comments are the correct way to create full documentation of your code within Xcode. For these, simply use two asterisks to start and end as you would for a regular block comment with a single asterisk. You can even use the markdown syntax to format your comment and make it more readable.

This is how you would document some code:

Start adding good comments to your code and you’ll be one step closer to writing readable code.

2. Naming Based on Role

You may have heard this a lot, but code needs to be able to read like English. Actually, the computer doesn’t care one bit about how it looks to humans, but one of the signs of a good programmer is how well they can articulate their code to be as readable as possible.

In Swift, it’s best to name things based on the role that the object plays in the code. For example, instead of simply using the name apple for a variable of type Apple, if the apple serves as food for an animal, it could be named food instead.

It can sometimes be tempting to give many responsibilities to an object which is supposed to be specialized, and this can make your app less modular and more confusing for anyone who’s reading the code. Naming your objects based on what they do can help remind you to only give roles to the objects which they’re responsible for.

Variables and Constants

The names of…properties, variables, and constants should read as nouns. — Apple

This general rule of thumb makes sense because of the role that these types play in an app are typically representable by nouns. Here are some examples:

  • var scoreCounter for a SpriteKit game state variable.
  • let sharedInstance for a singleton.

Booleans

Uses of Boolean methods and properties should read as assertions about the receiver. — Apple

By saying that booleans “should be assertions about the receiver”, we simply mean that they should be yes or no declarations. Let’s look at a few examples:

  • var isEmpty for an array.
  • let touchesEdge for a game sprite.

Protocols

Protocols that describe what something is should read as nouns. — Apple

If you’re using protocols to make a “template” type, you should use the same naming as you would use for variables and constants. This makes sense as well because you’re naming the type of the methods, classes, etc. Here are a few examples:

  • protocol Fruits for different types of fruit classes.
  • protocol Collections for arrays, lists, and more.

Protocols that describe a capability should be named using the suffixes: able, ible, or ing. — Apple

If your protocols are defining what a type is able to do, it should be named with the suffixes above. This should be read as if the protocol is “able” to do something. Here’s another list of examples:

  • protocol Returnable for types which can be returned.
  • protocol ProgressReporting for types which report progress.

Keep It Simple!

In addition to these naming conventions, Apple also recommends that you avoid what they call “terms of art,” or in other words, terms which may not be easily understandable. They don’t say to avoid them completely, but don’t use them when a basic word will suffice instead.

3. Use Design Patterns

In production-grade apps, developers use design patterns to structure their code in a way that can be changed and is also more readable. Let’s discuss a few design patterns that you can use in your next iOS app.

As cliché as this may sound, this really is the foundation of how you program your app. Let’s say you are building a home, your dream house. This house is five stories high, so if you don’t build a strong foundation and follow the blueprints, it will probably just topple over. The foundation of an iOS app is the design pattern or patterns that you choose. Let’s look at two of the most commonly used patterns.

MVC (Model-View-Controller)

The Model-View-Controller or MVC design pattern is an industry standard. It separates each part of your code into three parts: the model, the view, and the controller. 

  • Model: The model is essentially the data of the app. This handles things like reusable structures and classes that deal only with the data of the app. The model does not handle anything relating to the view or how the information will be shown to the user.
  • View: The view is responsible for only the visual representation of the data, and it also handles user interaction. It does not handle anything regarding data, nor does it deal with specific views. It is simply a reusable class which can be used multiple times without repeating code.
  • Controller: The controller is the boss. It brings data from the model, and then sends it to the view to finally display it to the user. This is typically in ViewController.swift, and it listens to input and changes the model as needed.

There are many variations of this, such as MVVM and MVP. It’s worth reading up on them, but the principle is similar to MVC. For more about MVC and MVVM, take a look these articles by Bart Jacobs here on Envato Tuts+.

  • Why MVC Might Not Be the Best Pattern for Cocoa Apps

    iOS SDK
  • Put Your View Controllers on a Diet With MVVM

    Mobile Development

Whichever one you choose, they are all called design patterns, and they make our code more modular. Let’s look at another design pattern which can complement the app pattern you choose to use.

Singletons

A singleton is a single instance of a class that is present at all times in memory. So why do we care about this? Well, let’s say that you are building an app that connects to a database. You need a place to put all of your data service connections. This would be a perfect place to use singletons. 

Look at the code below—it will show you how to construct a singleton:

It’s that easy!

If you use design patterns, your code will be much more readable, as well as organized and modular, so that you can isolate issues with your app much more easily and make large changes with minimal code rewiring. 

To learn more design patterns for Swift, check out our full-length course. 

  • Design Patterns
    Swift Design Patterns
    Derek Jensen

In this course, you’ll learn 21 different design patterns. You might just find one that will transform the way you code!

Conclusion

As you can see, it’s not that hard to make your code more readable and organized. When you make the effort to do so, you’ll have the benefit of easy-to-modify code, as well as making your code easier for others to understand. Employers look for these things, so get in the habit of applying these tips on a regular basis!

I hope you enjoyed this tutorial, and while you’re here, check out some of our other tutorials on Swift and iOS app development.

  • iOS SDK
    Updating Your App for iOS 11
    Doron Katz
  • Security
    Secure Coding in Swift 4
    Collin Stuart
  • iOS SDK
    Passing Data Between Controllers in Swift
    Francesco Franchini

Powered by WPeMatico

Leave a Comment

Scroll to Top