# Swift Sets

> Learn how to use sets in Swift to store unique, unordered items, from insert and contains to count, plus set math like union and intersection.

Author: Flavio Copes | Published: 2021-06-04 | Canonical: https://flaviocopes.com/swift-sets/

> This tutorial belongs to the [Swift](https://flaviocopes.com/swift-introduction/) series

Sets are used to create collections of non-repeated items.

While an array can contain many times the same item, you only have unique items in a set.

You can declare a set of Int values in this way:

```swift
let set: Set<Int> = [1, 2, 3]
```

or you can initialize it from an array:

```swift
let set = Set([1, 2, 3])
```

Add items to the set using `insert()`:

```swift
var set = Set([1, 2, 3])
set.insert(17)
```

Unlike arrays, there is no order or position in a set. Items are retrieved and inserted randomly.

The way to print the content of a set ordered is to transform it into an array using the `sorted()` method:

```swift
var set = Set([2, 1, 3])
let orderedList = set.sorted()
```

To check if a set contains an element, use the `contains()` method:

```swift
var set = Set([1, 2, 3])
set.contains(2) //true
```

To get the number of items in the set, use the `count` property:

```swift
let set = Set([1, 2, 3])
set.count //3
```

If a set is empty, its `isEmpty` property is `true`.

```swift
let set = Set([1, 2, 3])
set.isEmpty //false
```

To remove one item from the array, use `remove()` passing the value of the element:

```swift
var set = Set([1, 2, 3])
set.remove(1)
//set is [2, 3]
```

To remove all items from the set, you can use removeAll():

```swift
set.removeAll()
```

Sets, like arrays, are passed by value, which means if you pass it to a function, or return it from a function, the set is copied.

Sets are great to perform set math operations like intersection, union, subtracting, and more.

These methods help with this:

- `intersection(_:)`
- `symmetricDifference(_:)`
- `union(_:)`
- `subtracting(_:)`
- `isSubset(of:)` 
- `isSuperset(of:)` 
- `isStrictSubset(of:)` 
- `isStrictSuperset(of:)`
- `isDisjoint(with:)`

Sets are collections, and they can be iterated over in loops.
