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, Failed would be printed to the console since we are attempting to add the value One to the set when it is already in the set.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset