DEV Community

Neeraj Gupta for DSC CIET

Posted on

Sets in Swift

Brief Introduction About Swift

Swift is a language developed by Apple which is made using modern approach, include safety features and software design patterns. As the name suggests swift is fast, safe and easy to use. It is basically made a replacement for c-based family(C, C++ and Objective-C). It can be used to make apps and can be also used for cloud services and it is among the fastest growing languages.

Sets in Swift

Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations. Sets are mainly subset(part) of Dictionaries. In Sets every value defined is unique and they store value by hashing so values are not stored in a fixed order and their order can vary while accessing.

Syntax to Define Sets

var setName : Set<DataType> = [values]
Enter fullscreen mode Exit fullscreen mode

Here the data type passed need to be of Hashable type.

Hashing

Hashing means generating a unique id for every value .

Code Example

var SamsungSmartphone : Set<String> = ["Android", "Camera" , "Samsung Pay"] //hashing
var AppleIPhone : [String] = ["iOS" , "Camera" , "Apple Pay"]

print(SamsungSmartphone) // ["Camera", "Android", "Samsung Pay"]
print(AppleIPhone) // ["iOS", "Camera", "Apple Pay"]
Enter fullscreen mode Exit fullscreen mode

**Note: In your case order of printing can differ as sets are unordered due to hashing process.

Inbuilt Functions

//Below are two sets with similarities and some differences in both sets
var SamsungSmartphone : Set<String> = ["Android", "Camera" , "Samsung Pay"] //hashing
var AppleIPhone : [String] = ["iOS" , "Camera" , "Apple Pay"]

print(SamsungSmartphone)
print(AppleIPhone)

//Inbuilt Functions

// Intersection returns the element common in Both sets
print(SamsungSmartphone.intersection(AppleIPhone)) // ["Camera"]

// symmetricDifference returns all the elements that are not common in both sets
print(SamsungSmartphone.symmetricDifference(AppleIPhone)) // ["Samsung Pay", "Apple Pay", "iOS", "Android"]

// union returns all the elements in both sets
print(SamsungSmartphone.union(AppleIPhone)) // ["Android", "Samsung Pay", "Apple Pay", "Camera", "iOS"]

// Returns the elements in first set that do not match second set
print(SamsungSmartphone.subtracting(AppleIPhone)) // ["Android", "Samsung Pay"]

// Inserting Value in Set
SamsungSmartphone.insert("Samsung Watch")

// Finding Values in Set
print(SamsungSmartphone.contains("Android")) //true
print(SamsungSmartphone.contains("Andoid")) // false
Enter fullscreen mode Exit fullscreen mode

Custom Sets

Now Let's see how we can create custom sets.

struct Smartphone : Hashable {
    let name : String
    let model : String
}

let smartphoneObj : Set<Smartphone> = [Smartphone(name: "Apple", model: "iPhone"), Smartphone(name: "Samsung", model: "S9")]
for smartphone in smartphoneObj {
    print(smartphone.hashValue)
}


//Output:-
// Some random id
//Some random id
Enter fullscreen mode Exit fullscreen mode

Here, we created struct and declare some properties in it and note here we are conforming it to protocol Hashable so that when making object from it we can utilize the functionalities of Sets.

Here, output will be 2 random id's as we are passing different parameters in set parameters and we know every element is unique in Sets. So, what if we give both elements same values as parameters? Will it print 2 random id's or a single random id?

Let' see

struct Smartphone : Hashable {
    let name : String
    let model : String
}

let smartphoneObj : Set<Smartphone> = [Smartphone(name: "Apple", model: "iPhone"), Smartphone(name: "Apple", model: "iPhone")]
for smartphone in smartphoneObj {
    print(smartphone.hashValue)
}

//Output :- 
//Some random id
Enter fullscreen mode Exit fullscreen mode

It wil print one single id. Why? Because it maintains uniqueness and it will generate one hashValue corresponding to both means it will map both of them to same hash id as to maintain uniqueness.

This was all about sets in swift. Hope, this helped. Meet you guys in next post.

Discussion (2)

Collapse
fmo91 profile image
Fernando Martín Ortiz

Nice article! Concise and helpful.

Just one little thing, I think here you missed the closing parenthesis for the print statements?

// Finding Values in Set
print(SamsungSmartphone.contains("Android") //true
print(SamsungSmartphone.contains("Andoid") // false
Enter fullscreen mode Exit fullscreen mode
Collapse
neeraj15022001 profile image
Neeraj Gupta Author

Thanks Fernando for rectifying me.