Exploiting Swift in Projects with Classes and Extensions

Pablo Blanco
3 min readDec 28, 2019

Tutorial made with Swift 5

Problem

Repeat code, waste time, fail probability

Who hasn’t repeat some lines of code to set the label font or the label color, or to change the color of a button in dependence of it if is enabled or disabled ? I think almost everyone who works in programming.

Problem Example :

This example may seem like it’s not that bad but if your app has a lot of screens it becomes a problem. And imagine that you have to change the font for every label because the app is suffering a design change. You will waste a lot of time looking for each place where it is being used. It is also easy to fail with the value of a parameter and do not make equal styles.

If you are working in a big project or even in a small project with styles in common like: elements states, colors, fonts and behaviors you should try to promote the unification.

Guidelines

Save time, less code, unification, easy use, avoid fails

A nice solution that will save you time and lines of code is to follow this to guidelines:

  • Create custom simple elements and use them in your outlets, instead of using a UIView and set its appearance create an ExampleView and use it to inherit its properties.
  • Exploit the use of extensions with useful functions.

It may seem simple concepts but they are powerful and saves time.

To add your new custom classes it is advisable to have a file like a DesignSheet.swift or CustomViews.swift.

To exploit the use of extensions with useful functions: In some projects it is common to see files like UIView+Extension.swift. I prefer to have an Extensions.swift file, this depends on each one.

Let’s see how to solve this situation following the guidelines with the above examples.

Solution Example :

Create custom elements

Create the DesignSheet.swift file and add your elements

Easy to use:

  • Create your element and set the class desired, look that the Inherit Module from Target is checked:
  • After dragging your outlet check that its the same class:

The result will be the same but it will be easier, cleaner, faster and better.

ExampleView result

Use extensions

  • Create your file with extensions:
  • Use your extensions:

These guidelines will improve your project and your work:

  • Faster → Save time
  • Easy to use
  • Clean → Less code
  • Avoid style fails
  • Unification

Conclusion :

Remember to avoid duplicate code, if you are making the same thing more than once, try to make it generic and do not repeat it unless it’s necessary.

Make things reusable and easy to use, this will help you and your team work faster and the project will become cleaner and unified.

--

--