Skip to main content

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")

Example: Initializing with Values

let fruits = ["Apple", "Banana", "Cherry"]

Example: Creating with Initial Values

let numbers = [1, 2, 3, 4, 5]

2. Accessing Array Elements

Method Description Example
first Returns the first element of the array, or nil if the array is empty
let numbers = [1, 2, 3, 4, 5]
print(numbers.first) // Optional(1)
last Returns the last element of the array, or nil if the array is empty
let numbers = [1, 2, 3, 4, 5]
print(numbers.last) // Optional(5)
count Returns the number of elements in the array
let numbers = [1, 2, 3, 4, 5]
print(numbers.count) // 5
isEmpty Returns a Boolean value indicating whether the array is empty
let numbers: [Int] = []
print(numbers.isEmpty) // true
indices Returns a collection of the array's indices
let numbers = [10, 20, 30]
print(numbers.indices) // CountableRange(0...2)
element at index Accesses an element at a specific index using subscript syntax
let numbers = [1, 2, 3, 4, 5]
print(numbers[0]) // 1
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
var fruits = ["apple", "banana"]
fruits.append("cherry")
// fruits = ["apple", "banana", "cherry"]
insert(_:at:) Inserts an element at a specific index
var numbers = [1, 2, 4]
numbers.insert(3, at: 2)
// numbers = [1, 2, 3, 4]
remove(at:) Removes and returns the element at a specific index
var colors = ["red", "green", "blue"]
let removedColor = colors.remove(at: 1)
// removedColor = "green", colors = ["red", "blue"]
removeAll() Removes all elements from the array
var items = [1, 2, 3]
items.removeAll()
// items = []
sort() Sorts the array in place
var names = ["Charlie", "Alice", "Bob"]
names.sort()
// names = ["Alice", "Bob", "Charlie"]
reverse() Reverses the order of elements in place
var letters = ["a", "b", "c"]
letters.reverse()
// letters = ["c", "b", "a"]

4. Iterating Arrays

Method Description Example
for-in loop Iterates through each element in the array
let fruits = ["apple", "banana", "cherry"]
for fruit in fruits {
    print(fruit)
}
forEach Executes a closure for each element
let numbers = [1, 2, 3, 4]
numbers.forEach { number in
    print(number * 2)
}
indices Returns the indices of all elements
let colors = ["red", "green", "blue"]
for index in colors.indices {
    print("Color at index \(index): \(colors[index])")
}
enumerated Returns both index and element
let animals = ["cat", "dog", "bird"]
for (index, animal) in animals.enumerated() {
    print("\(index): \(animal)")
}

5. Transforming Arrays

Method Description Example
map Transforms each element into a new form
let numbers = [1, 2, 3]
let doubled = numbers.map { $0 * 2 }
// doubled = [2, 4, 6]
filter Creates a new array with elements that pass a test
let numbers = [1, 2, 3, 4, 5]
let evens = numbers.filter { $0 % 2 == 0 }
// eves = [2, 4]
compactMap Transforms and unwraps optional values
let strings = ["1", "2", "three"]
let numbers = strings.compactMap { Int($0) }
// numbers = [1, 2]
flatMap Flattens arrays after transformation
let arrays = [[1, 2], [3, 4]]
let flattened = arrays.flatMap { $0 }
// flattened = [1, 2, 3, 4]
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
let numbers = [1, 2, 3, 4, 5]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
// Result: [2, 4]
compactMap Transforms and filters elements in one step, removing nil values
let strings = ["1", "2", "three", "4"]
let numbers = strings.compactMap { Int($0) }
// Result: [1, 2, 4]
first(where:) Returns the first element that satisfies the condition
let numbers = [1, 3, 5, 6, 7]
let firstEven = numbers.first { $0 % 2 == 0 }
// Result: Optional(6)
first Returns the first element of the array
let numbers = [1, 2, 3]
let firstNumber = numbers.first
// Result: Optional(1)
last(where:) Returns the last element that satisfies the condition
let numbers = [1, 2, 3, 4, 5]
let lastEven = numbers.last { $0 % 2 == 0 }
// Result: Optional(4)
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.
let numbers = [1, 2, 3, 4]
let sum = numbers.reduce(0) { $0 + $1 }
print(sum) // Output: 10
reduce(into: Similar to reduce, but allows mutation of the accumulator.
let numbers = [1, 2, 3, 4]
let string = numbers.reduce(into: "") { $0 += "\\($1)" }
print(string) // Output: "1234"

8. Sorting Arrays

Method Description Example
sort() Sorts the array in place using a closure
var numbers = [3, 1, 4, 1, 5]
numbers.sort { $0 > $1 }
print(numbers) // [5, 4, 3, 1, 1]
sorted() Returns a new sorted array without modifying the original
let numbers = [3, 1, 4, 1, 5]
let sortedNumbers = numbers.sorted { $0 < $1 }
print(sortedNumbers) // [1, 1, 3, 4, 5]
sort(by:) Sorts using a custom comparison function
let names = ["Alice", "Bob", "Charlie"]
names.sort(by: <)
print(names) // ["Alice", "Bob", "Charlie"]
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
let keyValuePairs = [("one", 1), ("two", 2)]
let dictFromPairs = Dictionary(uniqueKeysWithValues: keyValuePairs)
Dictionary<K, V>(keys: [K], values: [V]) Creates a dictionary from separate arrays of keys and values
let keys = ["a", "b", "c"]
let values = [1, 2, 3]
let dictFromArrays = Dictionary(keys: keys, values: 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
let dict = ["a": 1, "b": 2]
let keys = dict.keys // ["a", "b"]
values Returns a collection of all values in the dictionary Dictionary.Values
let dict = ["a": 1, "b": 2]
let values = dict.values // [1, 2]
count Returns the number of key-value pairs in the dictionary Int
let dict = ["a": 1, "b": 2]
print(dict.count) // 2
isEmpty Indicates whether the dictionary is empty Bool
let dict: [String: Int] = [:]
print(dict.isEmpty) // true
contains(key:) Checks if a key exists in the dictionary Bool
let dict = ["a": 1, "b": 2]
print(dict.contains(key: "a")) // true
removeValue(forKey:) Removes a key-value pair and returns the value, or nil if not found Value?
var dict = ["a": 1, "b": 2]
let removedValue = dict.removeValue(forKey: "a") // Optional(1)
updateValue(_:forKey:) Updates the value for a key or adds a new key-value pair Value?
var dict = ["a": 1]
dict.updateValue(3, forKey: "a") // Optional(1)
dict.updateValue(4, forKey: "b") // nil
forEach(_:) Iterates over key-value pairs Void
let dict = ["a": 1, "b": 2]
dict.forEach { key, value in
    print("\(key): \(value)")
}
filter(_:) Returns a dictionary containing only key-value pairs that match the condition Dictionary
let dict = ["a": 1, "b": 2, "c": 3]
let filtered = dict.filter { $0.value > 1 } // ["b": 2, "c": 3]
mapValues(_:) Transforms all values in the dictionary Dictionary
let dict = ["a": 1, "b": 2]
let mapped = dict.mapValues { $0 * 2 } // ["a": 2, "b": 4]

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)

Example: Creating an Empty Set

var emptySet: Set<Int> = []
print(emptySet.isEmpty) // Output: true
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
let set1 = [1, 2, 3]
let set2 = [3, 4, 5]
let unionSet = set1.union(set2) // [1, 2, 3, 4, 5]
intersection Returns a set with elements common to both sets
let set1 = [1, 2, 3]
let set2 = [3, 4, 5]
let intersectionSet = set1.intersection(set2) // [3]
symmetricDifference Returns a set with elements in either set but not both
let set1 = [1, 2, 3]
let set2 = [3, 4, 5]
let symDiffSet = set1.symmetricDifference(set2) // [1, 2, 4, 5]
subtracting Returns a set with elements in the first set but not the second
let set1 = [1, 2, 3]
let set2 = [3, 4, 5]
let diffSet = set1.subtracting(set2) // [1, 2]
Note: Set operations in Swift return a new set and do not modify the original sets.

Was this article helpful?