Swift: Checking For Elements

Checking Elements from Swift’s Set:

The .contains() method can be used to check whether or not an element exists within a set in Swift.

To find an element within a set, we can use the following syntax:


  • The expression returns true if the item exists in the set.
  • The expression returns false if the item does not exist in the set.

Assume we’re throwing a party. Let’s make a set for all of the cold drinks we have in the house right now:

var coldDrinks: Set = ["Coca-Cola", "Mountain Dew", "Diet Coke", "Sprite"];

We’re about to go shopping and want to know if we already have "Fanta" or if we need to buy more. We can use the following if/else statement as our conditional with coldDrinks.contains("Fanta"):

if coldDrinks.contains("Fanta") {
  print("We don't require any more Fanta.");
} else {
  print("Let's buy more Fanta.");

// Prints: Let's buy more Fanta.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: