Choosing the Right Collection for Your Data
Swift provides three primary collection types. Choosing the wrong one leads to messy code or performance issues. Use this rule of thumb:
- Array: You care about order (list of dashboard widgets, chat messages).
- Set: You care about uniqueness and fast lookups (user IDs in a room, tags on a post).
- Dictionary: You need to look up values by an identifier (user profiles by ID, configuration flags).
For Flutter developers:
Array=List<T>,Set=Set<T>,Dictionary=Map<K,V>.
- Arrays – Ordered, Indexed, Duplicate-Allowed
Arrays are zero-indexed, ordered collections that can contain duplicate values. They are optimized for sequential iteration and access at the end of the array. Insertion or removal at the front is O(n) because elements shift.
- Dictionaries – Fast Key-Based Lookups
Dictionaries store unordered key-value pairs. Keys must be Hashable (String, Int, etc.). Lookup, insertion, and deletion are all O(1) on average – making them perfect for caches or data stores. Access always returns an Optional because the key might not exist.
- Sets – Uniqueness and Fast Membership Testing
A Set is an unordered collection of unique values. Its superpower is contains() – O(1) vs O(n) for an Array. Use Sets for tag systems, permission flags, or deduplicating data. Elements must be Hashable.
- Mutability & Performance: let vs var
Swift enforces mutability at the collection level:
var= Mutable (can add, remove, change elements).let= Immutable (fixed size and content – like a frozen list).
Copy-on-Write (COW): Assigning a var collection to a new variable doesn't copy the underlying data immediately. It only copies when one of the variables mutates it. This makes Swift collections extremely efficient – even large arrays are cheap to pass around.
- Functional Transformations (Map, Filter, Reduce)
Swift collections integrate seamlessly with functional programming. These methods are preferred over manual loops for cleaner, more declarative code – especially when transforming data between layers of your architecture (e.g., Repository → UseCase → Presenter).
- When to Use Each Collection – Architecture Decision Guide
| Use Case | Recommended Collection | Why | |----------|----------------------|-----| | List of dashboard widgets (order matters) | Array | Preserves display order, allows duplicates | | User session store (lookup by userID) | Dictionary | O(1) lookup by ID, no order needed | | Set of permissions for a user | Set | Fast contains() check, ensures uniqueness | | Chat message history | Array | Ordered, indexed access, supports pagination | | Tags on a blog post | Set | No duplicates, fast to check if tag exists | | Configuration flags (key: flag name, value: enabled) | Dictionary | Natural key-value mapping |