Swift Tips and Tricks #1

Eduardo Sanches Bocato
Level Up Coding
Published in
2 min readJan 5, 2020

--

You probably have already seen some or even all the things I'm going to present below. Those are some of the tips and tricks I passed along to my brother (who started his career as an iOS developer less than a year ago), friends, and colleagues.

These are just simple tips or tricks that can change the outcome of your code, or things I like to apply to my code on a daily basis.

1. Comparing optionals to exact values

You don't need to unwrap an optional value if you are going to compare it to an exact value.

It is common to find things like this:

var someOptionalString: String?
if
let stringValue = someOptionalString, stringValue.isEmpty { ... }

If your objective is just to check if the string is not empty and act on it, you can simply compare isEmpty with the exact outcome you expect, ending up with something like this:

var someOptionalString: String?
if
stringValue?.isEmpty == false { ... }

2. Think twice before declaring a Boolean as optional

When we create booleans, we normally want to verify if something is true or false, so there are 2 possible values for this property. Yeah, this sounds like a no-brainer, right?! Keep that in mind.

When a boolean is declared as optional, we end up with 3 possible values: true, false, and nil.

What I'm trying to say here is:

  • Is that what you really wanted? The nil is really necessary?
  • Do you really need 3 possible states?
  • Doesn't this property have a default value?

3. Using nested types for namespacing

In computing, a namespace is a set of symbols that are used to organize objects of various kinds, so that these objects may be referred to by name. A namespace ensures that all the identifiers within it have unique names so that they can be easily identified.
(Source: Wikipedia)

In Swift, this can be achieved using nested types.

As the definition says, namespaces can provide you with more context, which can make your code more concise and less error prone.

4. Providing default value for parameters in protocols

When extracting interfaces from something, it is very common to find methods with default parameters, and Swift protocols don't allow you to have this. In order to keep compatibility, it is best not to change this behavior.

You can solve this using protocol extensions and keep the method exactly as it were before.

5. Using interfaces for your singletons

First of all, not all problems needs to be solved with a singleton just because is simpler. But, when you really need one, it is very useful to create interfaces for them. These interfaces are very important to avoid side effects when creating your tests.

--

--

iOS Engineer, AI enthusiast, Crossfit/Gymnastics. Currently working as iOS Lead @adidas