Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
122: Implementing a Binary Search Tree in Swift
How do I structure the Node so Swift doesn't complain about optionality?
When you're building a BST, the biggest hurdle for a lot of Swift developers is the recursive nature of the nodes. Since a node might not have a left or right child, those properties must be optionals. I always recommend using a class here rather than a struct. Why? Because trees are inherently reference-based. If you use a struct, you'll run into a nightmare of mutating copies every time you try to move down a level.
Let's say we're building a system to track Book IDs in a library. Here is how I'd set up the basic node:
class BSTNode {
var value: Int
var left: BSTNode?
var right: BSTNode?
init(value: Int) {
self.value = value
}
}
Notice that left and right are BSTNode?. This is key. It allows the leaf nodes to simply be nil, which is our signal to stop recursing.
What's the most intuitive way to handle insertions?
The logic for insertion is a classic "left or right" decision. If the new value is less than the current node, you head left. If it's greater, you head right. The trick is handling the case where the child is currently nil—that's where the new node actually gets placed.
I prefer wrapping the BSTNode inside a BinarySearchTree class. It keeps the API clean so the user doesn't have to manually track the root node. Here is how I'd implement the insertion logic:
class BinarySearchTree {
var root: BSTNode?
func insert(_ value: Int) {
root = insertRecursive(root, value)
}
private func insertRecursive(_ node: BSTNode?, _ value: Int) -> BSTNode {
// If we've reached a nil spot, we've found the home for the new node
guard let node = node else {
return BSTNode(value: value)
}
if value < node.value {
node.left = insertRecursive(node.left, value)
} else if value > node.value {
node.right = insertRecursive(node.right, value)
}
// Return the node to maintain the link to the parent
return node
}
}
One little detail: I used else if value > node.value. I'm intentionally ignoring equal values here because standard BSTs usually don't allow duplicates. If you need duplicates, you'd have to decide if they always go right or if you'll add a counter to the node.
How do I actually retrieve a value from the tree efficiently?
This is where the BST really shines. Instead of checking every single element (like you would in an array), you can discard half the tree with every single step. It's the same logic as the insertion, but instead of creating a node, you're just returning a boolean or the node itself.
I like to write the search as a simple recursive helper. It's clean and reads almost like a sentence:
func contains(_ value: Int) -> Bool {
return searchRecursive(root, value)
}
private func searchRecursive(_ node: BSTNode?, _ value: Int) -> Bool {
guard let node = node else {
return false // We hit a leaf and didn't find it
}
if value == node.value {
return true // Found it!
}
return value < node.value
? searchRecursive(node.left, value)
: searchRecursive(node.right, value)
}
By using the ternary operator here, the code stays compact. You're essentially saying: "If the value is smaller, look left; otherwise, look right."
📋 Practical Task
Exercise: Building a Book ID Validator
Imagine you are managing a digital archive. You have a list of Book IDs that have already been registered: [50, 25, 75, 12, 37, 60, 90].
Your task is to:
- Implement the
BinarySearchTreeandBSTNodeclasses as discussed in the lesson. - Insert the provided list of Book IDs into your tree.
- Write a function called
validateBookExists(_ id: Int)that uses your BST search logic to returntrueif the ID is in the tree andfalseotherwise. - Test your implementation by checking for an ID that exists (e.g., 37) and one that doesn't (e.g., 100) and print the results to the console.
There are no comments for now.