Start learning free

LESSON 235 OF 678 · SETS

Sets in Swift

Lesson

TL ; DR:

A Set holds values without repeats. Inserting a value that is already in it changes nothing.


var pets = Set<String>()          // an empty set
pets.insert("cat")
pets.insert("dog")
pets.insert("cat")                 // already in it, no change

print(pets.count)                  // 2
print(pets.contains("dog"))        // true


Full lesson:

An array keeps every value you put in it, repeats too. Sometimes you only need to know which values there are. A set is made for that.

A set holds each value once. Inserting a value that is already in it changes nothing.

  • Set<String>() makes an empty set of strings.
  • s.insert(x) puts x in the set s.
  • s.contains(x) is true when x is in the set.
  • s.count gives how many values the set holds.
  • Set(array) builds a set from an array. Its repeats go in once.

Checking s.contains(x) is fast, even for a big set. An array's contains looks at the values one by one.

A set you change needs var. And ["cat", "dog"] on its own is an array. Set(...) turns it into a set.

A set has no order and no number indexes. A printed set may show its values in any order.


Your task

The camp's sign-up array, names, has some names twice. Build a set named kids from it.

Then Zoe signs up, and Ava signs up again. Insert both names into kids.

Last, if kids contains "Leo", print Leo is coming.

The code already prints the number of kids twice.

Expected output:

3 kids
4 kids
Leo is coming
STEP 1 OF 3
    Ctrl + Enter to check