CODEX

8 Swift Tips & Tricks for 2022

Learn eight useful tricks to write professional-looking code.

Artturi Jalli
CodeX
Published in
4 min readJan 28, 2021

--

Original Image: Ales Nesetril

I’ve collected a list of useful tips and “tricks” you can use to write professional Swift code.

I hope you enjoy it.

1. Shorter If…Else Statements with Ternary Operators

Ternary operators allow us to make if...else statements shorter.

The syntax is:

condition ? true : false

For example, let’s compress this if-else expression:

let money = 100if money > 0 {
print("Some money")
} else {
print("No money")
}

This can be written as a one-liner:

money > 0 ? print("Some money") : print("No money")

2. Destructuring Tuples

Let’s implement a function that returns a tuple that contains a name and an email address:

func getInfo() -> (name: String, email: String) {
return (name: "Matt", email: "matt@example.com")
}

When accessing the tuple, you can keep the info together by assigning the whole tuple to a single variable by:

--

--

Artturi Jalli
CodeX

Check @jalliartturi on YouTube to become a successful blogger. (For collabs, reach me out at: artturi@bloggersgoto.com)