In Swift, there are three main standard collections: Array, Set, and Dictionary. Each of them implements different interfaces, differs in internal structure, and is intended for different tasks.
Background:
In Swift, collections are designed with a focus on type safety and performance, including value semantics and Copy-on-Write copying for Arrays/Sets/Dictionaries.
Problem:
Often, a beginner developer uses only Array where it would be more appropriate to use Set or Dictionary, which leads to memory overuse and reduced access/search speed. It's important to understand the differences.
Solution:
An ordered collection of elements, indexed access, duplicates are allowed. Typically implemented with a dynamic buffer.
An unordered collection of unique elements (Hashable). Access is by hash — very fast, duplicates are not allowed.
A collection of key-value pairs. The key must be Hashable. Access to the value by key (via hash table).
Example code:
var arr: [Int] = [1, 2, 3, 4] var set: Set<Int> = [1, 2, 2, 3] var dict: [String: Int] = ["a": 1, "b": 2] // set == [1, 2, 3] — duplicates are discarded
Key features:
Can non-Hashable types be used as elements of Set or Dictionary?
No. To be stored in Set/Dictionary, an element must be Hashable (have a unique hash identifier). Otherwise, the compiler will not allow the collection to be created.
struct Point {} // Set<Point> will cause an error because Point is not Hashable
Is the order of storage of elements in Set the same as when they are added?
No. Set does not guarantee order — iteration can provide any order. If you need order, use Array.
What happens when trying to access a non-existing key in Dictionary?
Dictionary will return an Optional. Be careful — trying to access a non-existing key will yield nil, not an error.
let val = dict["not exist"] // val — nil
A developer uses Array for a unique list of users and checks uniqueness through contains. On large lists, this takes a lot of time for checks.
Pros:
Cons:
The same list is implemented as a Set. Checking for existence is instantaneous, unique values are guaranteed.
Pros:
Cons: