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 {
    print(food)
}

let hasBananas = groceryBag.contains("Bananas")

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

Unions

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.