O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Getting a Set

It is time to make an instance of Set. Create a new playground called Groceries.

Type in the following to get an instance of Set.

Listing 11.1 Creating a set

import Cocoa

var str = "Hello, playground"

var groceryBag = Set<String>()

You made an instance of Set and declared that it will hold instances of the String type. It is a mutable Set called groceryBag and is currently empty. Let’s fix that.

You can add groceries to your groceryBag using the insert(_:) method.

Listing 11.2 Adding to a set

...
var groceryBag = Set<String>()
groceryBag.insert("Apples")
groceryBag.insert("Oranges")
groceryBag.insert("Pineapple")

You may notice that the results sidebar shows something like (.0 true, .1 "Apples") ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required