Working with Sets

Now that you have an instance of Set, you might be wondering how to work with the elements inside of it. For example, you might want to know if your groceryBag contains a particular item. The Set type provides a method called contains(_:) that looks inside of a set instance for a particular item.

Listing 11.5  Has bananas?

var groceryBag: Set = ["Apples", "Oranges", "Pineapple"]

for food in groceryBag {

let hasBananas = groceryBag.contains("Bananas")

The value of hasBananas is false; your groceryBag does not have any bananas inside of it.


Imagine that you are wandering around the grocery store and you bump into a friend. You get to talking, and your friend suggests that you ...

Get Swift Programming: The Big Nerd Ranch Guide now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.