Set in Swift :
Previously we have discussed about arrays in swift. Similar to array, set is another collection data type in swift. The main difference is that the elements in a set are unordered and it contain only unique elements. In this tutorial, we will show you how to create a set and different set operations :
Creating a set :
Set is denoted as Set , where Element is the type of elements . We can create an empty set like below :
import UIKit
var name = Set()
print (name.count)
It will print ‘0’. We can also create a set directly with an array literal :
import UIKit
var days : Set = ["Monday","Tuesday","Wednesday"]
print (days)
It will print :
["Monday", "Tuesday", "Wednesday"]
Since all the values of the array are of same type, we can also declare the set without using the type :
import UIKit
var days : Set = ["Monday","Tuesday","Wednesday"]
print (days)
Output will be same as above. What will be the output for the example below :
import UIKit
var days : Set = ["Monday","Tuesday","Wednesday","Monday"]
print (days)
Since set contains only unique elements, it will include only one ‘Monday’ instead of two :
["Tuesday", "Monday", "Wednesday"]
Accessing and Modifying a set :
Check if it is empty and get the count of a set :
To check if a set is empty or not in swift, ‘isEmpty’ is used. To get the total number of elements of a set, ‘.count’ is used.
import UIKit
var days : Set = ["Monday","Tuesday","Wednesday","Monday"]
var months = Set()
if(!days.isEmpty){
print ("days is not empty and count is \(days.count)")
}
if(months.isEmpty){
print ("months is empty")
}
It will give the following output :
days is not empty and count is 3
months is empty
Inserting and removing an element to swift set :
For inserting an element, ‘insert()’ is used and for deleting an element ‘remove()’ is used. We can also check if an item is in a set or not using ‘contain()’ method.
import UIKit
var days : Set = ["Monday","Tuesday","Wednesday"]
days.insert("Thrusday")
print ("days after inserted ",days)
days.remove("Monday")
print ("days after removed ",days)
if(days.contains("Tuesday")){
print ("set days contain string \"Tuesday\"")
}
days.insert("Monday")
print ("added monday again ",days)
Output :
days after inserted ["Tuesday", "Monday", "Wednesday", "Thrusday"]
days after removed ["Tuesday", "Thrusday", "Wednesday"]
set days contain string "Tuesday"
added monday again ["Tuesday", "Thrusday", "Wednesday", "Monday"]
Iterating a swift set :
To iterate through a set, we can use one for in loop similar to array. Also, before iterating, you can sort the set if you want.
import UIKit
var data : Set = ["Banana","Monkey","Apple","Cat"]
for item in data.sorted() {
print (item)
}
Output :
Apple
Banana
Cat
Monkey