5 Useful Swift One-Liners to Code Like a Pro
Learn a bunch of one-liners to improve code readability
1. One-Liner If-Else Operator
Did you know that you can replace this simple if-else statement:
let money = 100
if money > 0 {
print("Some money")
} else {
print("No money")
}
With this neat little one-liner expression?
money > 0 ? print("Some money") : print("No money")
This is an operator 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
2. Swap Two Variables Without a Helper
In order to swap two variables without a helper variable, you can utilize tuple destructuring:
var a = 1
var b = 2
(a, b) = (b, a)
print(a, b)
Output:
2 1
3. Check for Nils in Optional Values
You don’t need to write if-else statements to check if an optional value is nil
. Instead, you can use a nil coalescing operator, ??
, to achieve the same with just one line of code:
var name: String?
print(name ?? "N/A")
Output:
N/A
Nil coalescing is a commonly used feature in Swift. It works by checking if the left-hand side of ??
is nil
. If it is, then it returns the value on the right-hand side. Otherwise, it returns the value on the left.
In other words, print(name ?? "N/A")
is just a nice shorthand for:
var name: String?
if name != nil {
print(name)
} else {
print("N/A")
}
4. Check if a Word Exists in a Sentence
You can check if a particular word exists in a string with a simple one-liner:
let favorites = ["Banana", "Orange", "Apple"]
let bag = "I packed some Beef, Potatoes, and a Banana"
let hasFavorite = !favorites.filter({bag.contains($0)}).isEmpty
print(hasFavorite)
Output:
true
5. Sum All Numbers Up to a Number
For example, sum up numbers from 1 to 10:
let sum = (1...10).reduce(0,+)
print(sum)
Output:
55
Conclusion
Thanks for reading. Happy coding!