Introduction to Algorithms and Data Structures in Swift
Swift is a powerful and intuitive programming language created by Apple for developing applications for iOS, macOS, watchOS, and tvOS. However, to write efficient and fast code, knowing just the syntax is not enough. Understanding algorithms and data structures is the foundation that turns a beginner into a professional developer.
In this article, we will cover basic data structures (arrays, dictionaries, sets) and key algorithms (sorting, searching) in Swift. All code examples are ready to run in Xcode Playground.
Basic Data Structures in Swift
Swift provides built-in data structures that are optimized for memory and performance. Let's look at the three most important ones.
Arrays (Array)
An array is an ordered collection of elements of the same type. In Swift, arrays are strongly typed and have a fixed order.
// Creating an arrayvar numbers: [Int] = [1, 2, 3, 4, 5]
// Adding an elementnumbers.append(6)
// Access by indexlet first = numbers[0] // 1
// Iterationfor number in numbers { print(number)}
// In-place sortingnumbers.sort() // [1, 2, 3, 4, 5, 6]Arrays are ideal when the order of elements matters and fast access by index (O(1)) is needed. However, inserting or deleting at the beginning of an array takes O(n) time.
Dictionaries (Dictionary)
A dictionary stores key-value pairs. Keys must be unique and hashable (e.g., String, Int).
// Creating a dictionaryvar scores: [String: Int] = ["Alice": 95, "Bob": 87]
// Adding or updatingscores["Charlie"] = 92
// Getting a value (optional)if let aliceScore = scores["Alice"] { print("Alice's score: \\(aliceScore)")}
// Deletingscores.removeValue(forKey: "Bob")Dictionaries provide access to a value by key in O(1) on average. Use them when data is naturally grouped by unique keys.
Sets (Set)
A set is an unordered collection of unique elements. It is useful for membership testing and removing duplicates.
// Creating a setvar fruits: Set<String> = ["Apple", "Banana", "Orange"]
// Addingfruits.insert("Mango")
// Checking for membershipif fruits.contains("Apple") { print("Apple is in the set")}
// Removing duplicates from an arraylet arrayWithDuplicates = [1, 1, 2, 3, 3, 4]let uniqueSet = Set(arrayWithDuplicates) // {1, 2, 3, 4}Basic Algorithms in Swift
Now let's apply data structures to solve typical problems. We'll look at sorting and searching.
Sorting Algorithms
Swift has a built-in sort() function, but for understanding, let's write the classic Quick Sort algorithm.
func quickSort(_ array: [Int]) -> [Int] { guard array.count > 1 else { return array } let pivot = array[array.count / 2] let less = array.filter { $0 < pivot } let equal = array.filter { $0 == pivot } let greater = array.filter { $0 > pivot } return quickSort(less) + equal + quickSort(greater)}
let unsorted = [3, 6, 1, 8, 2, 9, 4]let sorted = quickSort(unsorted)print(sorted) // [1, 2, 3, 4, 6, 8, 9]Quick Sort is one of the most efficient algorithms with an average complexity of O(n log n). For small arrays, you can use the built-in sorted().
Searching Algorithms
Linear search is simple but slow (O(n)). For sorted data, use binary search (O(log n)).
// Binary searchfunc binarySearch(_ array: [Int], target: Int) -> Int? { var low = 0 var high = array.count - 1 while low <= high { let mid = (low + high)