Collection Types: Arrays & Dictionaries
Master Swift Collections for iOS App Development
Swift Collection Types Overview
Arrays
Ordered collections of data accessed by zero-indexed positions. Perfect for storing sequential information like playlists or game levels.
Dictionaries
Unordered collections using key-value pairs for data access. Ideal for storing related attributes like user profiles or settings.
Xcode Playground Setup
Create New Playground
Launch Xcode and navigate to File > New > Playground, selecting Blank template under iOS
Save to Project Directory
Navigate to Desktop > Class Files > yourname-iOS App Dev 1 Class and save as Collection Types.playground
Initialize Workspace
Click Create to begin working with Swift collections in the interactive playground environment
Arrays in Swift are zero-indexed, meaning the first item has an index of 0, the second item is 1, and so forth. This is fundamental to understanding array access patterns.
Array Index Visualization
Constants vs Variables for Arrays
| Feature | let (Constants) | var (Variables) |
|---|---|---|
| Mutability | Immutable | Mutable |
| Use Case | Fixed data | Changing data |
| Methods Available | Read-only | Append, Remove, Insert |
Array Modification Methods
append()
Adds new elements to the end of an array. Always places items at the final position.
remove(at:)
Removes elements at a specific index position. Automatically shifts remaining elements to fill gaps.
insert(_:at:)
Inserts elements at any specified position within the array, shifting existing elements as needed.
When creating arrays without initial values, you must specify the data type explicitly since Swift cannot infer the type from empty collections.
Arrays vs Dictionaries
| Feature | Arrays | Dictionaries |
|---|---|---|
| Data Organization | Ordered by index | Unordered key-value pairs |
| Access Method | Numeric index | String or other key |
| Use Case | Sequential data | Related attributes |
| Performance | Index-based lookup | Key-based lookup |
Dictionary Operations
updateValue()
Modifies existing values for specified keys. Returns the old value to confirm the update operation.
removeValue()
Deletes key-value pairs from the dictionary. Completely removes both the key and its associated value.
Direct Assignment
Add new key-value pairs using bracket notation. Creates new entries or updates existing ones seamlessly.
Empty dictionaries require explicit type declaration using [KeyType: ValueType]() syntax, defining both key and value data types upfront.
Collection Best Practices
Improves code readability and maintenance
Avoids hardcoding array lengths and prevents index errors
Arrays for ordered data, dictionaries for key-value relationships
Ensures Swift can validate operations and prevent type errors
Key Takeaways
if the output is truncated.