O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

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

Inserting items into a set

We use the insert method to insert an item into a set. If we attempt to insert an item that is already in the set, the item will be ignored. Here are some examples of inserting items into a set:

var mySet = Set<String>()  
mySet.insert("One")  
mySet.insert("Two")  
mySet.insert("Three") 

The insert method returns a tuple that we can use to verify that the value was successfully added to the set. We will look at tuples later in this chapter, but the following example shows how to check the returned value to see if it was added successfully:

var mySet = Set<String>() 
mySet.insert("One") 
mySet.insert("Two") 
var results = mySet.insert("One") 
if results.inserted { 
  print("Success") 
} else { 
  print("Failed") 
} 

In this example, ...

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