Ad space (banner)
๐ŸฆSwift Lessons
Lesson 27 / 68

Working with Set

In this lesson you will learn how to hold duplicate-free data with Set in Swift, and understand the basics of the set data structure. This is for anyone searching for "Swift Set how to use".

Set is a box that refuses to hold the same value twice. It is handy for stripping duplicates out of an array, or for checking membership quickly.

The sample code builds a set from the duplicate-containing array [1, 2, 2, 3, 3, 3] with Set(nums); the duplicates disappear automatically and only 1, 2, and 3 remain. Notice how contains() checks whether a value is present.

A common stumbling block for beginners is that the order of a Set is not guaranteed. Unlike an array, items are not necessarily kept in insertion order, so an array is a better fit when order matters.

In real-world development, Set's contains also outperforms an array's once there is a lot of data, making it very handy for removing duplicates.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)