Working with Collections
1. Creating Arrays
| Method | Description | Example |
|---|---|---|
| Array() | Creates an empty array with a specified type | let numbers = Array<Int>() |
| [] | Creates an empty array using shorthand syntax | let names: [String] = [] |
| Array(repeating:count:) | Creates an array with repeated values | let zeros = Array(repeating: 0, count: 5) |
| Array(of:) | Creates an array with a single element | let singleArray = Array(of: "Swift") |
2. Accessing Array Elements
| Method | Description | Example |
|---|---|---|
| first | Returns the first element of the array, or nil if the array is empty | |
| last | Returns the last element of the array, or nil if the array is empty | |
| count | Returns the number of elements in the array | |
| isEmpty | Returns a Boolean value indicating whether the array is empty | |
| indices | Returns a collection of the array's indices | |
| element at index | Accesses an element at a specific index using subscript syntax | |
Note: Accessing an element at an invalid index will cause a runtime error. Always ensure the index is within bounds.
3. Modifying Arrays
| Method | Description | Example |
|---|---|---|
| append(_:) | Adds an element to the end of the array | |
| insert(_:at:) | Inserts an element at a specific index | |
| remove(at:) | Removes and returns the element at a specific index | |
| removeAll() | Removes all elements from the array | |
| sort() | Sorts the array in place | |
| reverse() | Reverses the order of elements in place | |
4. Iterating Arrays
| Method | Description | Example |
|---|---|---|
| for-in loop | Iterates through each element in the array | |
| forEach | Executes a closure for each element | |
| indices | Returns the indices of all elements | |
| enumerated | Returns both index and element | |
5. Transforming Arrays
| Method | Description | Example |
|---|---|---|
| map | Transforms each element into a new form | |
| filter | Creates a new array with elements that pass a test | |
| compactMap | Transforms and unwraps optional values | |
| flatMap | Flattens arrays after transformation | |
Note:
compactMap is often preferred over map followed by filter when dealing with optionals.6. Filtering Arrays
| Method | Description | Example |
|---|---|---|
| filter | Returns a new array containing elements that satisfy the condition | |
| compactMap | Transforms and filters elements in one step, removing nil values | |
| first(where:) | Returns the first element that satisfies the condition | |
| first | Returns the first element of the array | |
| last(where:) | Returns the last element that satisfies the condition | |
Note:
filter and compactMap return new arrays, while first(where:) and last(where:) return optional values.7. Reducing Arrays (reduce)
| Method | Description | Example |
|---|---|---|
| reduce(_: | Combines all elements of the array into a single value using a closure. | |
| reduce(into: | Similar to reduce, but allows mutation of the accumulator. | |
8. Sorting Arrays
| Method | Description | Example |
|---|---|---|
| sort() | Sorts the array in place using a closure | |
| sorted() | Returns a new sorted array without modifying the original | |
| sort(by:) | Sorts using a custom comparison function | |
Note:
sort() modifies the array in place, while sorted() returns a new array.9. Creating Dictionaries
| Method | Description | Example |
|---|---|---|
| Dictionary() | Creates an empty dictionary | var emptyDict = Dictionary<String, Int>() |
| Dictionary<K, V>(minCapability: Int) | Creates a dictionary with initial capacity | var dictWithCapacity = Dictionary<String, Int>(minCapability: 10) |
| Dictionary<K, V>(uniqueKeysWithValues: [(K, V)]) | Creates a dictionary from an array of key-value pairs | |
| Dictionary<K, V>(keys: [K], values: [V]) | Creates a dictionary from separate arrays of keys and values | |
Example: Creating a Dictionary with Initial Values
let scores = ["Alice": 95, "Bob": 87, "Charlie": 92]
Note: Dictionary literals are a convenient way to create dictionaries with initial values.
10. Working with Dictionary Methods
| Method | Description | Return Type | Example |
|---|---|---|---|
| keys | Returns a collection of all keys in the dictionary | Dictionary.Keys |
|
| values | Returns a collection of all values in the dictionary | Dictionary.Values |
|
| count | Returns the number of key-value pairs in the dictionary | Int |
|
| isEmpty | Indicates whether the dictionary is empty | Bool |
|
| contains(key:) | Checks if a key exists in the dictionary | Bool |
|
| removeValue(forKey:) | Removes a key-value pair and returns the value, or nil if not found | Value? |
|
| updateValue(_:forKey:) | Updates the value for a key or adds a new key-value pair | Value? |
|
| forEach(_:) | Iterates over key-value pairs | Void |
|
| filter(_:) | Returns a dictionary containing only key-value pairs that match the condition | Dictionary |
|
| mapValues(_:) | Transforms all values in the dictionary | Dictionary |
|
11. Creating Sets
A Set in Swift is a collection that stores unique values of the same type in a collection with no defined ordering.
| Property | Description | Example |
|---|---|---|
| Set<Element> | Defines a set that holds elements of type Element. |
Set<String> |
| emptySet | Creates an empty set of a specified type. | var names: Set<String> = [] |
| setWithElements | Creates a set with initial elements. | let numbers: Set<Int> = [1, 2, 3, 4, 5] |
Example: Creating a Set
let fruits: Set<String> = ["apple", "banana", "orange"]
print(fruits) // Output: ["banana", "orange", "apple"] (order may vary)
Note: Sets are unordered collections, and elements in a set are unique.
12. Using Set Operations
| Operation | Description | Example |
|---|---|---|
| union | Returns a set with elements from both sets | |
| intersection | Returns a set with elements common to both sets | |
| symmetricDifference | Returns a set with elements in either set but not both | |
| subtracting | Returns a set with elements in the first set but not the second | |
Note: Set operations in Swift return a new set and do not modify the original sets.