Week 8: Your Swift Code Works, But It Doesn’t Make Sense.

Swiftos
Geek Culture
Published in
2 min readMay 17, 2021

--

Photo by Farzad Nazifi on Unsplash

Hi Junior iOS Developers,

“Your code works, but it doesn’t make sense.” You may have heard this from a senior developer. If you are coming from a low-level programming language or you just started learning Swift, this story should be beneficial for you. In this story, we’ll talk about some readability issues. The code should work perfectly fine but just doesn’t make sense.

There are multiple ways to check if an element exists in an array. Here are my suggestions for some common cases.

To check if names contains “Mike”:

let names = ["Dylan", "Jenny", "Amy", "Mike", "Jenny"]

Contains Over Filter Count

// Not recommanded
names.filter { $0 == "Mike" }.count > 0
// Recommanded
names.contains { $0 == "Mike" }

Contains Over Filter Is Empty

// Not recommanded
names.filter { $0 == "Mike" }.isEmpty
// Recommanded
names.contains { $0 == "Mike" }

Contains Over first not nil

// Not recommanded
names.first (where: { $0 == "Mike" })
// Recommanded
names.contains { $0 == "Mike" }

--

--

Swiftos
Geek Culture

I publish short iOS development tutorials on a weekly basis. For all content, head over to: https://www.patreon.com/Swiftos