A set stores unique values of the same type in no specific order. This makes Set
a better option than Array
when two conditions are true:
- The order of the collection does not matter
- The collection should not contain duplicate values
Syntax
Let’s declare a set that holds String
:
</div> language-'></div>">We specify the type of values the set holds within angle brackets, prefaced by `Set`. We can create an empty set with initialization syntax using parenthesis, just like an array:
<div class='oc-markdown-activatable oc-markdown-custom-container' data-value='```swift
let names = Set<String>()
'>
Sets don’t have a shorthand for type annotation or initialization like arrays do, so we need to use the full form.
Set Creation with Array Literals
We can use array literals to initialize our set:
</div> language-'></div>">Notice that we don’t need to annotate the type of values that the Set holds when initializing it with an array literal. Swift can infer the type based on the literal. Thus, we only need to write `Set` for the type annotation. We can’t rely solely on type inference here though; if we didn’t specify `Set` then Swift would infer `numbers` to be an array.
Remember that a set cannot contain duplicate values. If your array literal contains duplicate values then only one of the values will be in the resulting set.
<div class='oc-markdown-activatable oc-markdown-custom-container' data-value='```swift
let numbers: Set = [1, 1, 2, 3, 3]
print(numbers) // [1, 2, 3]
'>