How to Create a Set in Swift

Updated: May 9, 2023 By: Khue Post a comment

This concise and straight-to-the-point article shows you how to create a set in Swift.

Creating and initializing an empty set

You can create an empty set by using either the generic syntax or an array literal. It’s also important to tell Swift what type of data is going to be stored.

Example:

// using generic syntax
var numbers = Set<Int>() 
print("Type of variable numbers is \(type(of: numbers))")

// using an empty array literal
var words: Set<String> = [] 
print("Type of variable words is \(type(of: words))")

Output:

Type of variable numbers is Set<Int>
Type of variable words is Set<String>

Creating a set with literal values

When we create a set with some initial data, Swift can infer the data type (so that we don’t have to explicitly tell it). If you want to initialize an immutable set, use the let keyword. Otherwise, use the var keyword.

Example:

// an immutable set
let colors = Set(["blue", "green", "red", "yellow"])

// a mutable set
var numbers = Set([1, 2, 3, 4, 5])