Member-only story
5 Tips To Write Clean Swift Code
Swift tricks to improve our code writing skills
A good software engineer is not just a person who can solve problems efficiently writing software. They are people who can write code that is robust, easy to read, and easy to maintain more than writing smart one-line solutions.
Good software engineers spot where they can simplify the code, use patterns, or refactor pieces of code to make them better.
Let’s explore five of my favorites ways to write cleaner and more meaningful code in Swift.
Use Positive Guards
The guard
keyword is one of the most defining of the Swift programming language. We use it every day, and it has two main usages:
- Unwrap optionals we need for some computation.
- State preconditions for our functions.
The tip I’m about to share is more meaningful for the second kind of usage.
Think about the precondition we write in our algorithms: !set.isEmpty
, !name.isEmpty
, num != nil
, and so on. How many times have you written the following code?
I think many times. This fragment of code, together with all of the examples above, has at least two downsides:
- It is error-prone — it’s easy to forget the
!
. - It is hard to internalize. When reading the condition, we have to invert the semantic of the words we read to understand the code’s meaning properly.
Lucky for us, we can easily solve this by adding a trivial helper to the Collection
protocol. Here’s the code:
We solved both the downsides in a single shot with this simple expedient, and we made our code straightforward.