CollectionType - Set in Swift.

Swift providing three type of Collection known as Array (Array in Swift) , Set and Dictionary (Dictionary in Swift) to storing the value. Array store the value in the order. Set store the value unordered but unique. and Dictionary store the value in unordered  with key-value.

Set Definition : 
“A set stores unique values of same type in a collection with no ordering. Sets should be used when there is no defined order, Sets store distinct value." 
Swift set is written as `Set` where `Element` is the type that the set will store.

Create and Initializing Empty Set :
var fruits = Set<String>()
Create  Set with values :  The fruits set store only the String value like Apple , Banana , etc.
var fruits : Set<String> = ["Apple", "Orange", "PineApple" ,  "Banana"]
Create Set with multiple type :  if you don't define Set then allowed multiple dataType values in Set like String , Int , etc.
var multipleSet : Set = ["Cat","Dog","Parrot" , 3 , 4]
Count :  Set have own count method to get number of element in Set.
print("I have \(fruits.count) fruits.")
Insert Element :   To insert new element in fruit Set.
Remove Element :   To remove element from fruit Set.
Check Element availability :   To check element has in Set or Not.
if fruits.contains("Mango") {    print("Yes")
Iterating Set :   iterating Set using for-in loop.
for element in fruits {    print("\(element)")
Sort :  Set doesn't have a predefine ordering. So use of Sort() function to arrange element ordering.
Operation on Set :  

IntersectingIntersecting two sets will give result of common element in two set.
var fruitsSet1 :Set = ["Apple","Mango","Banana","PineApple"]
var fruitsSet2    :Set = ["Mango","Banana"]
var CommonElement = fruitsSet1.intersect(fruitsSet2)
print("\(CommonElement)") // will print "Mango" & "Banana"
Exclusive Or : It's give the result in value in either Set but not in both.
var fruitsSet3  :Set = ["Apple","Mango","Banana","PineApple"]
var fruitsSet4     :Set = ["Mango","Banana" , "Orange"]
var exclusive = fruitsSet3.exclusiveOr(fruitsSet4)
print("\(exclusive)")   // will print {"Apple", "Orange", "PineApple"}
Union : It's give the result of both set all value in unique.
var fruitsSet5  :Set = ["Apple","Mango","Banana","PineApple"]
var fruitsSet6  :Set = ["Mango","Banana" , "Orange"]
var union = fruitsSet5.union(fruitsSet6)
print("\(union)") // will print {"Apple", "Orange", "Mango", "Banana", "PineApple"}
Subtract : It's create a new Set in which value doesn't have specific set.
var fruitsSet7 :Set = ["Apple","Mango","Banana","PineApple"]
var fruitsSet8 :Set = ["Mango","Banana" , "Orange"]
var subtract1 = fruitsSet7.subtract(fruitsSet8)
print("\(subtract1)") // will print {"Apple" , "PineApple"}

CollectionType - Set in Swift. CollectionType - Set in Swift. Reviewed by KIRIT MODI on 01:43:00 Rating: 5

No comments:

Powered by Blogger.