Swift – Print Set

In Swift, you can print an entire Set with the print() function or print its elements individually by iterating over the Set. A for-in loop is usually the clearest option when you need one element per line.

In this tutorial, we will learn how to print all elements of a Set in Swift programming.

To print all elements of a Set we shall iterate through all of the elements in the Set, using for loop, while loop or forEach loop, and print each of them.

A Swift Set is unordered. The values may therefore appear in a different order each time the program runs. If the output must follow a predictable order, sort the Set before printing it.

Print an Entire Swift Set with print()

Pass the Set directly to print() when you only need a quick representation of all its values.

</>
Copy
let colors: Set<String> = ["Red", "Green", "Blue"]

print(colors)

Possible output

["Blue", "Red", "Green"]

The exact order is not guaranteed because a Set does not preserve insertion order.

Example 1: Print Set using for Loop

In this example, we have a set of even numbers. We shall use a Swift For Loop to iterate through the elements of the Set and print them.

main.swift

</>
Copy
var evens: Set = [2, 4, 8, 14]

for even in evens {
    print("even")
}

Output

14
2
4
8

To print the value stored in the loop variable, pass even without quotation marks. Writing "even" prints the literal word instead.

</>
Copy
let evens: Set<Int> = [2, 4, 8, 14]

for even in evens {
    print(even)
}

Possible output

14
2
4
8

Note that in a Swift Set, order of the elements is not saved. So, when you iterate through a Set, you get the elements of the Set randomly.

But it can be guaranteed that an element does not occur twice.

Example 2: Print Set using while Loop

In this example, we have a set of student names. We shall use a Swift While Loop and size of the Set to iterate through the elements of the Set and print them.

main.swift

</>
Copy
var students: Set = ["John", "Surya", "Lini"]

var i=0

while i<students.count {
    print(students[students.index(students.startIndex, offsetBy: i)])
    i=i+1
}

Output

John
Surya
Lini

Note that the Swift Set is unordered and the index on the Set does not make sense. But if you want an implementation using the index, this is the example.

Set indices are collection-specific values rather than integer positions. For that reason, a for-in loop is generally simpler and clearer than manually advancing from startIndex in a while loop.

Example 3: Print Set using forEach

In this example, we have a set of odd numbers. We shall use a Swift ForEach to iterate on a Set and print all of the elements in it.

main.swift

</>
Copy
var odds: Set = [3, 9, 7, 5]

odds.forEach{ odd in
    print(odd)
}

Output

5
7
3
9

The closure passed to forEach runs once for every element. As with a for-in loop, the iteration order is not guaranteed.

Print a Swift Set in Sorted Order

Call sorted() before printing when the values must appear in a predictable order. The method returns a sorted Array, which can then be iterated.

</>
Copy
let scores: Set<Int> = [80, 45, 100, 60]

for score in scores.sorted() {
    print(score)
}

Output

45
60
80
100

For descending order, provide the greater-than operator to sorted(by:).

</>
Copy
for score in scores.sorted(by: >) {
    print(score)
}

Output

100
80
60
45

Print One Element from a Swift Set

Because a Set is unordered, it has no meaningful “first inserted” element. You can use first to retrieve an arbitrary element as an optional value.

</>
Copy
let languages: Set<String> = ["Swift", "Kotlin", "Java"]

if let language = languages.first {
    print(language)
}

Possible output

Swift

The value may differ between runs. Use languages.sorted().first when you need the first value according to a defined sorting order.

Print Swift Set Elements on One Line

Use the terminator argument of print() to place the elements on one line.

</>
Copy
let numbers: Set<Int> = [10, 20, 30]

for number in numbers.sorted() {
    print(number, terminator: " ")
}

Output

10 20 30 

For a cleaner string without a trailing separator, convert the values to strings and join them.

</>
Copy
let text = numbers
    .sorted()
    .map(String.init)
    .joined(separator: ", ")

print(text)

Output

10, 20, 30

Swift Set Printing and Duplicate Values

A Set stores each distinct value only once. Duplicate values supplied during initialization are removed before the Set is printed.

</>
Copy
let numbers: Set<Int> = [1, 2, 2, 3, 3, 3]

for number in numbers.sorted() {
    print(number)
}

Output

1
2
3

Frequently Asked Questions about Printing Sets in Swift

How do I print a Set in Swift?

Pass the Set directly to print() to display its collection representation, or iterate over it with a for-in loop to print one element at a time.

Why does a Swift Set print in a different order?

A Set is an unordered collection, so its iteration and printed order are not guaranteed. Call sorted() before printing when order matters.

How do I print only one value from a Swift Set?

Read the Set’s first property and unwrap the optional value. The returned element is arbitrary unless the Set is sorted first.

Can I access a Swift Set with an integer index?

Not directly. A Set uses its own index type and does not provide integer subscripting such as set[0]. Use iteration, first, or convert the Set to an Array when positional access is required.

How do I print Swift Set values separated by commas?

Sort the Set if necessary, convert each element to a String, and call joined(separator: ", ").

Swift Set Printing Editorial QA Checklist

  • Confirm that examples do not claim a fixed iteration order unless sorted() is used.
  • Verify that loop variables are printed without quotation marks when their values are required.
  • Check that examples retrieving first safely unwrap its optional result.
  • Do not use integer subscripting such as set[0] for Swift Sets.
  • Label unordered examples as possible output rather than guaranteed output.

Summary of Swift Set Printing Methods

Use print(set) for a quick representation of the entire Set. Use a for-in loop or forEach to print individual values, and call sorted() first when the output must be predictable. Remember that Sets are unordered, contain unique values, and do not support integer-based subscripting.

In this Swift Tutorial, we have learned to print a set using for loop, forEach and while loop with the help of Swift example programs.