Bad practice: not using .isMultiple(of:)


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


Can you guess what could be improved with this code?

We’re doing a test to determine whether an integer is even or odd.

This kind of test is quite common: for instance, if you want to implement a list with a different background color on every other row.

However, you can notice that the way the test is written feels very low level.

We’re using the modulo operator (%) to get the remainder of the integer divided by two and then we test whether that remainder is equal to zero.

This way of writing the computation would be quite acceptable in many programming languages, however in Swift we have a better alternative!

Because in Swift, integers actually have access to a method called .isMultiple(of:).

As its name suggests, this method returns a boolean and tests whether the integer is a multiple of the value passed as an argument:

And as you can see, when we use this method, the code looks much cleaner and its intent has become much more obvious!

That’s all for this article, I hope you’ve enjoyed discovering this new API!

Here’s the code if you want to experiment with it:

// Before
import Foundation

let myInteger = Int.random(in: 0...10)

if myInteger % 2 == 0 {
    print("it's even")
} else {
    print("it's odd")
}

// After
import Foundation

let myInteger = Int.random(in: 0...10)

if myInteger.isMultiple(of: 2) {
    print("it's even")
} else {
    print("it's odd")
}
Previous
Previous

When should you use a hybrid framework? 🤔

Next
Next

How to write safer code using the Lock 🔒 and Key 🔑 pattern