Daniel's working notes

Swift semantics

Interesting points on how to make Swift code easier to read.

To achieve this, we could could utilize extensions.

There are three points the author suggest

  • Inverse semantics

Inverse semantics will help us to read negation or ! operator easier in control flow.

For example, to check if array is empty, we can use myArray.isEmpty.

But if we need to check if array is not empty, we need to use ! like this: !myArray.isEmpty which quite hard to read or at least takes 1-2 seconds to get it.

To solve this readibility, we can define an extension on Array and use them similar with isEmpty property.

extension Array {
  var isNotEmpty: Bool {
    return !isEmpty

// Then you can use it like so:

if myArray.isNotEmpty { /** do something */ }
  • Syntax hiding semantics

This point address readibility in comparison operator such as == or !=. date.isToday is easier to read than date == todayDate.

On author’s example also showing us a useful extension for comparing optional value. if myOptional.isNil { ... }

  • Chaining semantics

Use chaining operator when it makes sense. Especially when we need to cast a type to another type which contains optional value.




Linked Notes: