Sling Academy
Home/Swift/How to Create a Set in Swift

How to Create a Set in Swift

Last updated: May 09, 2023

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])

Next Article: Adding new Elements to a Set in Swift

Previous Article: Swift: Converting a Dictionary into an Array

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)
  • Swift: 5 Ways to Iterate over an Array