9 Swift One-Liners That Will Make You Look Like an Expert

9 Swift One-Liners That Will Make You Look Like an Expert

Swift is an incredibly powerful and expressive programming language that enables developers to write concise and elegant code. In this blog post, we will dive into nine one-liners that demonstrate Swift's capabilities and make you look like an expert in the process. Let's get started!

1. Swapping values without a temporary variable:

Swift makes it incredibly easy to swap values of two variables without using a temporary variable. Using tuple destructuring, you can swap values in just one line:

(a, b) = (b, a)

For example, if you have:

var a = 5
var b = 10
(a, b) = (b, a)

After executing the one-liner, the values would be:

print(a) // Output: 10
print(b) // Output: 5

2. Short-circuit optional unwrapping:

In Swift, you can unwrap an optional value and execute a closure if the value is not nil. This can be achieved in just one line using optional chaining:

optionalValue.map { print("The value is: \($0)") }

For example:

let optionalValue: Int? = 42
optionalValue.map { print("The value is: \($0)") } // Output: The value is: 42

3. Filtering an array with a single condition:

You can filter an array based on a single condition in just one line using the filter function:

let filteredArray = array.filter { $0 % 2 == 0 }

For example:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers) // Output: [2, 4, 6, 8, 10]

4. Converting an array of strings to uppercase:

Swift's map function allows you to apply a transformation to each element in an array. This one-liner converts all strings in an array to uppercase:

let uppercasedArray = array.map { $0.uppercased() }

For example:

let names = ["Alice", "Bob", "Charlie"]
let uppercasedNames = names.map { $0.uppercased() }
print(uppercasedNames) // Output: ["ALICE", "BOB", "CHARLIE"]

5. Summing an array of integers:

Swift's reduce function allows you to accumulate a single value by successively combining elements in an array. This one-liner calculates the sum of an array of integers:

let sum = array.reduce(0, +)

For example:

let numbers = [1, 2, 3, 4, 5]
let sum = numbers.reduce(0, +)
print(sum) // Output: 15

6. Safely accessing an array element:

Swift provides a safe way to access an array element using optional subscripting. This one-liner defines an extension for Array that allows you to access an element safely:

extension Array { subscript(safe index: Index) -> Element? { indices.contains(index) ? self[index] : nil } }

Now you can use it like this:

let array = [1, 2, 3, 4, 5]
print(array[safe: 2]) // Output: Optional(3)
print(array[safe: 10]) // Output: nil

By using this one-liner extension, you can prevent index out of bounds errors while accessing array elements.

7. Checking if all elements in an array meet a condition:

Swift's allSatisfy function allows you to determine if all elements in an array meet a specified condition. This one-liner checks if all elements in an array are even:

let allEven = array.allSatisfy { $0 % 2 == 0 }

For example:

let numbers = [2, 4, 6, 8, 10]
let allEven = numbers.allSatisfy { $0 % 2 == 0 }
print(allEven) // Output: true

8. Joining an array of strings with a separator:

Swift makes it easy to join an array of strings with a separator using the joined function. This one-liner joins an array of strings with a comma and space:

let joinedString = array.joined(separator: ", ")

For example:

let names = ["Alice", "Bob", "Charlie"]
let joinedNames = names.joined(separator: ", ")
print(joinedNames) // Output: "Alice, Bob, Charlie"

9. Creating a dictionary from two arrays:

You can create a dictionary from two arrays (keys and values) using the zip function and a dictionary initializer. This one-liner creates a dictionary from two arrays:

let dictionary = Dictionary(uniqueKeysWithValues: zip(keysArray, valuesArray))

For example:

let keys = ["a", "b", "c"]
let values = [1, 2, 3]
let keyValuePairs = Dictionary(uniqueKeysWithValues: zip(keys, values))
print(keyValuePairs) // Output: ["a": 1, "b": 2, "c": 3]

These nine one-liners showcase the power and expressiveness of the language. With these one-liners in your arsenal, you can write concise and elegant code that demonstrates your expertise in Swift programming. Keep practising and exploring more advanced Swift techniques to further expand your skillset and elevate your code to the next level.

I hope you enjoyed this article, and if you have any questions, comments, or feedback, then feel free to comment here or reach out via Twitter.

Thanks for reading!