Cool Swift Array Tricks

Swift is a powerful programming language that provides a wide range of useful features and functionality. One of the most commonly used data structures in Swift is the array. In this article, we will explore some cool Swift array tricks that can help you write more concise and efficient code.

Initialising an Array with Repeated Values

If you want to create an array with a repeated value, you can use the init(repeating:count:) initializer. Here’s an example:

let zeros = Array(repeating: 0, count: 5)
print(zeros) // [0, 0, 0, 0, 0]

Merging Two Arrays

You can merge two arrays into a single array using the + operator. Here’s an example:

let firstArray = [1, 2, 3]
let secondArray = [4, 5, 6]
let mergedArray = firstArray + secondArray
print(mergedArray) // [1, 2, 3, 4, 5, 6]

Filtering an Array

You can filter an array based on a condition using the filter(_:) method. Here’s an example:

let numbers = [1, 2, 3, 4, 5]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers) // [2, 4]

Sorting an Array

You can sort an array using the sort(by:) method. Here’s an example:

var numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers.sort()
print(numbers) // [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

Reversing an Array

You can reverse the order of elements in an array using the reversed() method. Here’s an example:

let numbers = [1, 2, 3, 4, 5]
let reversedNumbers = numbers.reversed()
print(Array(reversedNumbers)) // [5, 4, 3, 2, 1]

Splitting an Array

You can split an array into two separate arrays using the split method. Here’s an example:

let numbers = [1, 2, 3, 4, 5]
let splitIndex = 3
let splitNumbers = numbers.split(at: splitIndex)
print(splitNumbers.left) // [1, 2, 3]
print(splitNumbers.right) // [4, 5]

These are just a few of the many cool Swift array tricks you can use to write more efficient and concise code. By taking advantage of these features, you can become a more productive and efficient Swift developer.

A pat on the back !!