Introduction
In this article, we will learn how to implement the concept of Sets in Swift programming language. Like other languages, Set is a new concept and it's totally related to math. Likewise in math, we see sets and operations like union, intersection, etc. The snapshots in my article are of Xcode Editor. I will run all the lines of code and show its snapshots to you.
What are Sets?
Set is an unordered collection of unique values of the same type. It is extremely useful when you ensure that the repeating items in a set only appear one time and the order of items is not important.
Creating Sets
The declaration of Set is similar to an array; the only key difference between the array and the set is, when you declare a Set you use a keyword “Set” which means the list of items is treated like a Set.
let setOne: Set<Int>
You can also initialize a set similar to an array, like
let set=Set<Int> ()
Set Literals
Sets don’t have their own literals, so we use array literals to create a set with initial values.
let array= [11,22,33,44]
This is simple array. So, we use array literals to create a set, like this:
let arrayset : Set<Int>=[11,22,33,44]
Accessing Element
Elements in sets don’t have any indices or keys. We have some built-in methods in array like isEmpty(). These types of methods are used in a set, too. I will apply some methods on set.

Code
- let SetA:Set<Int>=[11,22,33,44]
- print(SetA)
- print(SetA.first)
- print(SetA.first!)
- print(SetA.contains(11))
- print(SetA.contains(77))
Adding and removing elements in a set is same as an array. We use insert() method to add the element in set and remove() method to delete an item from set. We can see it through an example and apply add and remove method on it.

Code
- var SetA:Set<Int>=[11,22,33,44]
- print(SetA.insert(88))
- print(SetA)
- SetA.remove(88)
- print(SetA)



Vignesh ManiPosted Jul 11, 2016, 5:41 PM
Nice
kalu singh raoPosted Jul 9, 2016, 8:57 PM
Nice...