This course is all about writing quality code. Being able to write quality code and solve all types of bugs enables you to work efficiently and autonomously.
Code writing style
A big part of being able to produce quality code is definitely establishing your own consistent writing habits. There are different suggestions for many aspects of code convention and formatting.
Here's an example of two code snippets that are technically equivalent, but look different:
Which one is correct? 🤔
It's like cats vs. dogs... You're a cat-lover, I hope! 😸
Just kidding. 😇 Both coding styles are correct. However, using both in the same project is not desirable.
It's best if all the participants agree on a particular approach and follow it through.
For bigger projects, however, it may be harder to accomplish. In reality, some inconsistency is acceptable, but only if they are generally segmented (i.e. the whole module follows one style).
Another damaging approach is to think that if the code works, why should the writing style matter?
Imagine reading a book with well-structured pages and consistent formatting. Now imagine a badly formatted, inconsistent version of the same book! The content would be the same - the very same information is available to you, right? But think of your reading speed, your ability to digest the information, and so on. Think of the headaches! How long would you last before throwing the book across the room? Before hunting down the author?! 👿
Let's get back to code. The fun truth is that 80% of a developer's time is spent reading the code and finding bugs - your own or someone else's. To make your own life more productive, you have to optimize your code for readability.
If you are working on a team, there are likely to be differences in preferences. However, a unified decision is to be made and reinforced in the friendliest way possible.
A style guide
A set of stylistic rules to follow in coding is called a style guide.
Not to reinvent the wheel, there're predefined guides formed by other teams and many of them are made public.
For programming in Swift, there are two particularly popular ones:
Ray Wenderlich Swift StyleGuide - very extensive and very popular.
Github Swift StyleGuide - also very popular and used in SwiftLint, a tool that we'll explore shortly.
They describe details on syntax to follow. They range from the number of line breaks to separate methods to variable naming conventions, to how to unwrap an optional.
Once you've learned about the style recommendations, you'll feel the urge to apply this new knowledge to your code to make it beautiful! But you are human and will likely not remember everything at all times. 😇 Creating supporting environment will help you overcome these short comings!
Now we're going to learn a tool called SwiftLint, which is used to enforce Swift style and conventions. It analyzes your code, validates it against predefined rules and marks the validation results accordingly.
You can access it on GiHub: SwiftLint.
In order to integrate it with Xcode, we need to install it. To do this, we'll need to follow the installation instructions provided by the creators and available in a README file in the repository.
There are a few ways to install it. Let's choose the first one, which uses HomeBrew. HomeBrew is a package manager for Mac. Its role is to install and update small programs like SwiftLint.
HomeBrew installation instructions are available on the HomeBrew website - a simple command line to run in the Terminal.
What's the Terminal? 🙃
Terminal is a command line application for Mac. It implements an interface for giving commands to an operating system. It's a sort of low-level communication with Operating System.
So, the command we need to execute to install HomeBrew is this:
/ usr / bin / ruby -e "$ (curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Simply copy/paste it in the Terminal and click Enter to execute.
The script by that address will take care of the rest of the process. It will stop to ask you to press Enter one more time and then to provide a password for your computer.
And that's it, HomeBrew is installed!
Now we can install SwiftLint. Don't leave the Terminal just yet, the next installation is also done here. Simply copy this command in there and click Enter:
brew install swiftlint
Easy enough! SwiftLint is installed on your Mac!
Add SwiftLint to your project
One more action to complete: add SwiftLint in our application project. So that SwiftLint can read the code in our project and report style irregularities.
Remember, there are two phases of an app preparation - compilation and execution. It's at the compilation phase that the code is interpreted and translated into machine code.
Our goal here is to add a sequence to the compilation phase: SwiftLint static analysis. To add this sequence to the compilation process, we'll need to complete the following:
Select the project in the browser.
Select the target.
Select the build phases tab.
Tap more (+).
Choose New Run Script Phase.
Here's an illustration for your reference:
Once that's done, our new sequence at the compilation (or build) phase will be created:
We now need to modify it to use SwiftLint. For that, copy the following script to the place provided for this purpose:
ifwhichswiftlint>/dev/null;then swiftlint else echo"warning:SwiftLintnotinstalled,downloadfromhttps://github.com/realm/SwiftLint" fi
At the end, the phase should look like this:
That's it ! SwiftLint is ready to use! Great work! 😎
We've installed SwiftLint as the last step in compiling our code, so for it to work, we need to compile the code. For this we have two options:
Launch the app by pressing the Run button (or use a shortcut cmd + r). And you remember that to launch an app, it needs to be compiled first. So, even though we are requesting to launch the app, we are getting it compiled - making a build.
Only make a build - compile the app. For that, just use a shortcut cmd + b.
The second option is enough. It also saves time as we don't actually need the app launched.
Now observe the results of SwiftLint's work - we've got quite a number of 'errors.' The good news is that these are often easy to resolve. The three most common are:
line_length: A line that is too long, SwiftLint encourages lines smaller than 120 characters to fit on the screen.
vertical_whitespace: too many line breaks between two lines of code.
trailing_whitespace: an empty line that contains spaces: unnecessary spaces must be removed.
These errors and warnings are simple, so go ahead and fix them on your own!
Thanks to this SwiftLint analysis, our code will now be more polished and consistent!
Good to know...
A few more things worth mentioning:
Levels of error
SwiftLint uses the two levels of Xcode errors:
Warnings, which do not prevent the launch of the app.
Red errors, which prevent the launch of the app.
For example, if a line is too long and exceeds 120 characters, we'll have a 'warning.' But if it exceeds 200 characters, it's considered unnecessarily long and we get a 'red error.'
Build time vs Run time
If you go to the Error Navigator, you will find two sub-tabs. They distinguish between build-time (compilation) errors and run-time errors. And as you can see, all SwiftLint errors are on the compilation side:
Choose your rules
SwiftLint is installed with more than 75 predefined rules. You can change or disable them. I won't be covering that in this course. GitHub repository provides a detailed and the most up-to-date explanation and instructions - feel free to explore: SwiftLint rules.
One of the most important aspects of quality code is clean and consistent syntax and formatting.
To ensure code uniformity, we can use a syntactic guide (or syntax guide).
SwiftLint is a tool that allows static analysis of the code, based on the rules defined in a syntax guide.