Implementing Doubly Linked Lists in Swift
Article Summary
Oleg Tsibulevskiy from Just Eat Takeaway breaks down why choosing the wrong data structure could be killing your iOS app's performance. Spoiler: Arrays aren't always the answer.
This deep dive explores doubly linked lists in Swift, comparing their performance characteristics against dynamic arrays. Tsibulevskiy walks through a complete implementation with practical code examples, from basic operations to Swift protocol conformance.
Key Takeaways
- Insert at beginning: DLL achieves O(1) vs Array's O(n) complexity
- Complete implementation includes AddFirst, AddLast, Insert, Delete, and iteration
- Swift Sequence protocol enables native map and for-loop support
- Perfect for music players, browser history, and card game mechanics
Doubly linked lists outperform arrays for insertion/deletion operations but trade off direct index access, making them ideal for sequential navigation use cases.
About This Article
iOS developers often struggle to pick between doubly linked lists and dynamic arrays. Inserting at the beginning of an array costs O(n) time because every element has to shift, and the array might need to resize.
Oleg Tsibulevskiy built a generic Swift doubly linked list class with Head, Tail, Selected, and Length properties. It conforms to Sequence and IteratorProtocol so it works naturally with Swift's iteration features.
Developers can now pick the right data structure for what they're building. A doubly linked list gives O(1) insertion at the start while arrays keep O(1) index access. This matters for music players, browser caches, and card games where performance counts.