Junior — Middle
What other types of collections, besides arrays, sets, and dictionaries, are present in Swift?
sobes.tech AI
Answer from AI
In Swift, besides arrays (Array), sets (Set), and dictionaries (Dictionary), there are other collection types that can be used for storing and organizing data:
- Range — represents a range of values, for example,
1...5. - OptionSet — a structure for working with a set of options implemented through bit masks.
- ContiguousArray — an optimized array for storing elements in a contiguous memory area.
- ArraySlice — a slice of an array that allows working with a part of the array without copying.
- UnsafeBufferPointer and UnsafeMutableBufferPointer — low-level pointers for working with memory, which can be used as collections.
Additionally, you can create your own collections by implementing protocols like Collection, Sequence, and others, which allows creating structures with collection behaviors, such as a queue, stack, or linked list.
Example of creating a simple queue based on an array:
struct Queue<T> {
private var elements: [T] = []
mutating func enqueue(_ value: T) {
elements.append(value)
}
mutating func dequeue() -> T? {
guard !elements.isEmpty else { return nil }
return elements.removeFirst()
}
}