Swift Basics - Sets

Using the set type: each item must be unique. The items are not ordered.
The type stored in the set must be hashable.
A basic type (like string, int, double, float) are all hashable. They are able to compute hash values for themselves.

To create an initialise a set:
var mySet = Set<String>()
//initialise values
var mySet = Set(["ABC", "DEF", "GHI"])
//instead of var, you can use let

Insert items into a set. If we try to insert something that is already there, it will be ignored.
mySet.insert("JKL")

To check to see if it has been inserted successfully:
var results = mySet.insert("JKL")
if results.inserted{}

Get the number of items in a set:
mySet.count

Check to see if a set contains an item:
var contain = mySet.contains("ABC")
//will return true

Iterating over each item in a set:
for item in mySet
{
}

Removing items in a set:
var item = mySet.remove("ABC")
mySet.removeAll()

Construct sets from 2 sets:
var set1 = Set(["ABC", "DEF"])
var set2 = Set(["ABC", "GHI"])

var unionOfSet1andSet2 = set1.union(set2)
The duplicate values will not be duplicated
To unite without forming a new set:
set1.formUnion(set2)

Create a set with values from the first set that are not in the second set:
var afterSubtract = set1.subtracting(set2)
Without creating a new set:
set1.subtract(set2)

Intersection: Values that are common in both sets:
var afterIntersect = set1.intersection(set2)
Without creating a new set:
set1.formIntersection(set2)

Symmetric Differences: Values that are in either set, but not in both:
var afterExclusiveOr = set1.symmetricDifference(set2)
Without creating a new set:
set1.formSymmetricDifference(set2)

Comments

Popular posts from this blog

Setting up a playground

Go to another page