Nonsensical Swift Code

Erik Engheim
2 min readMay 14, 2016

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.

if dataTask != nil {
dataTask?.cancel()
}

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

dataTask?.cancel()

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:

class SpriteName {
class var PlayButton: String { return "PlayButton" }
class var SettingsButton: String { return "SettingsButton" }
}

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

enum SpriteName: String {
case PlayButton = "PlayButton"
case SettingsButton = "SettingsButton"
}

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.

if let value = variables[name] {
return value
} else {
return 0.0
}

It is easier to write this as

return variables[name] ?? 0.0

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.

if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
self.updateSearchResults(data)
}
}

We could avoided this nesting by using the where claus.

if let httpResponse = response as? NSHTTPURLResponse 
where httpResponse.statusCode == 200 {
self.updateSearchResults(data)
}

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.

--

--

Erik Engheim

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