Member-only story

5 Useful Swift One-Liners To Write Concise Code

Artturi Jalli
Better Programming
Published in
2 min readApr 9, 2021
Laptop on desk
Photo by Maxwell Nelson on Unsplash.

1. One-Liner If-Else Operator

Did you know that you can replace this simple if-else statement:

With this neat little one-liner expression?

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

This is actually known as a ternary conditional operator in Swift (it’s a common feature in other programming languages too).

Here is the general structure of a ternary conditional:

condition ? true_expression : false_expression

Be mindful when using this, though. This shorthand is a useful way to replace simple if-else statements. However, it’s not wise to make the code less readable by overusing it.

2. Swap Two Variables Without a Helper

In order to swap two variables without a helper variable, you can utilize tuple destructuring:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Write a response