All programmers develop specific habits after years of programming. Often these habits have formed around the particular feature set of the programming language you have used for the longest time. When switching to a new language like Swift it may not be apparent that there are better ways of doing things.

I will present various code snippets I have collected from different corners of the internet, which reflects a coding habit from another programming language which carries over poorly to Swift.

Pointless nil checks

From e.g. Java or C++ we are used to always carefully checking for nil or NULL before doing anything because if you forget, things have a tendency to blow up in your face.

But this is pointless in Swift. It is cleaner to write:

This will only run if dataTask != nil

Using class as a namespace for constants

In Java it is common to use a class to create a namespace for constants. In one example I encountered, they would write constants like this:

We have a much better way of doing this in Swift utilizing enums:

A benefit of this approach is that it works better with type inference: Any place that takes SpriteName type we could write .PlayButton, while with the class approach we always have to write SpriteName.PlayButton. Also by using enums we get the compiler to type check for us so that we don’t use a different constant than we intended.

Pointless if statements

Here is an example, which I think is done in all sorts of language. Often there are other alternatives, even if not all have the Swift ?? operator.

It is easier to write this as

A more common problem across all languages is nesting if-statements to deal with multiple boolean expression rather than simply using the && operator. Here is a more Swift specific case.

We could avoided this nesting by using the where claus.

Perhaps you also have examples of code habits which doesn’t make sense anymore with the feature set of Swift. I’d love to get your feedback, so I can expand this list.

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store