Swift - Data Type Sets

Introduction

A set stores a collection of unique values of the same type.

Sets are unordered and can store anything types.

You can create an empty set by using the Set type's initializer.

Demo

var setOfStrings = Set<String>()

You can create a set with an array literal.

Swift will figure out what type to use based on the type of values in the array:

Demo

var fruitSet  : Set = ["apple","orange","orange","banana"] 
print(fruitSet.count)

Result

Objects in a set are unique.

If you add the same object twice to a set, it's only included in the set once.

To be stored in a set, a type must be hashable.

All the build-in types are hashable, and you can make your own types hashable by making them conform to the Hashable protocol.

To modify a set, check if it's empty and add and removing items:

Demo

var fruitSet  : Set = ["apple","orange","orange","banana"] 
print(fruitSet.count)/*from  w  w w  . j ava2 s .  c  om*/

if fruitSet.isEmpty { 
    print("My set is empty!") 
} 

// Add a new item to the set 
fruitSet.insert("pear") 
print(fruitSet)
// Remove an item from the set 
fruitSet.remove("apple") 
print(fruitSet)// fruitSet now contains {"banana", "pear", "orange"}

Result

To get an element from a set you can use its index.

You need to first get the index of the element:

Demo

var fruitSet  : Set = ["apple","orange","orange","banana"] 
fruitSet.insert("pear") 
print(fruitSet)/*from   w ww.j ava2  s.  c om*/
// getting the index of "pear" 
let index = fruitSet.index(of: "pear") 
// index is now an optional Set.Index type 
print(fruitSet[index!]) // "pear"

Result

You can iterate over a set:

Demo

var fruitSet  : Set = ["apple","orange","orange","banana"] 
fruitSet.insert("pear") 
for fruit in fruitSet { 
    let fruitPlural = fruit + "s" 
    print("You know what's tasty? \(fruitPlural.uppercased()).") 
}

Result