Collection Types
In Swift, Collection types are used for storing collections of values. The Swift Standard Library provides three primary collection types: Array, Set, and Dictionary.
Array
An array is an ordered collection of items, which can be of any type. Arrays in Swift can grow and shrink dynamically.
Creating Arrays
var emptyArray = [Int]()
var anotherEmptyArray: [Int] = []
var arrayWithValues = [1, 2, 3, 4, 5]
Accessing and Modifying Arrays
// Accessing
let firstElement = arrayWithValues[0]
// Modifying
arrayWithValues.append(6)
arrayWithValues[0] = 0
// Removing
arrayWithValues.remove(at: 0)
// Iterating
for element in arrayWithValues {
print(element)
}
Set
A set is an unordered collection of unique elements. Like arrays, sets in Swift are strongly typed.
Creating Sets
var emptySet = Set<Int>()
var anotherEmptySet: Set<Int> = []
var setWithValues: Set = [1, 2, 3, 4, 5]
Accessing and Modifying Sets
// Adding elements
setWithValues.insert(6)
// Removing elements
setWithValues.remove(1)
// Checking for an element
if setWithValues.contains(4) {
print("Contains 4.")
}
// Iterating
for value in setWithValues {
print(value)
}
Dictionary
A dictionary is an unordered collection of key-value pairs. Dictionary keys must be unique and hashable.
Creating Dictionaries
var emptyDict = [String: Int]()
var anotherEmptyDict: [String: Int] = [:]
var dictWithValues: [String: Int] = ["One": 1, "Two": 2, "Three": 3]
Accessing and Modifying Dictionaries
// Accessing
let value = dictWithValues["One"]
// Modifying
dictWithValues["Four"] = 4
// Removing
dictWithValues["One"] = nil
// Iterating
for (key, value) in dictWithValues {
print("\(key): \(value)")
}
Common Collection Methods and Properties
Arrays, sets, and dictionaries share some common methods and properties:
- isEmpty: Check if the collection is empty
- count: Get the number of elements
- removeAll(): Remove all elements
if arrayWithValues.isEmpty {
print("The array is empty.")
}
let numberOfElements = arrayWithValues.count
arrayWithValues.removeAll()
These are the essential collection types in Swift, each with its own use-case, advantages, and disadvantages. You can also create custom collections by conforming to protocols like Collection, Sequence, etc.