Swift Tips and Tricks #2

Eduardo Sanches Bocato
2 min readFeb 6, 2020

This is part #2 of a series on tips and tricks to improve your Swift code.
You can check the first post here.

6. When to use functions and computed properties

Use a computed property when the operation:

  • Has low computational cost, O(1) complexity, for example.
  • Doesn't have side effects like throwing exceptions, calling other functions and such.
  • Returns a cached or preexistent information, some simple value or state.

Use a function when the operation:

  • Has high computational cost.
  • A complex logic is performed, like calling other methods.
  • Can throw exceptions.

Summing it all up: it all depends on what is being executed.
Basically, if the operation is simple and with low computational cost, aim for a computed property, otherwise use a function.

7. Use the final keyword

The reason is simple:

  • Do all your classes need to be extensible?
  • Can’t a functionality be added by composition instead of inheritance?

With this in mind, consider always using the final keyword on your class declarations and remove it when you are sure that the class can be inherited.

8. Structure constants in enums instead of structs

When you create constants it's very common find them inside structs, like the example below.

Constants in a Struct.

What can go wrong with it?
It's not that bad, but an struct can be instantiated.
Since we are using it just for namespacing purposes, that's not something we want, since it can cause some confusion… In order to remove this we would have to create a private initializer.

Constant in a Struct with private initialiser.

If we use a caseless enum, we won't have this kind of problem, since it can't be instantiated, causing an error.

Constants in a enum.
Error caused by trying to instantiate a caseless enum.

--

--

Eduardo Sanches Bocato

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