Better Programming

Advice for programmers.

Follow publication

Member-only story

5 Tips To Write Clean Swift Code

Riccardo Cipolleschi
Better Programming
Published in
7 min readApr 13, 2021

A laptop
Photo by Maxwell Nelson on Unsplash

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:

  1. Unwrap optionals we need for some computation.
  2. 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:

  1. It is error-prone — it’s easy to forget the !.
  2. 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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Riccardo Cipolleschi
Riccardo Cipolleschi

Written by Riccardo Cipolleschi

Hey there, I’m Riccardo. Software engineer at Meta. I have a passion for iOS and I love to share my knowledge with others.

No responses yet

Write a response