A simple way to use set
// Create an empty set var letters = set<character>() // array literal creates Set and can only hold string var setcolors:set <String> = [" red "," white "," Magenta "," yellow "]
//inferred to hold a string typevar setcolors:set = ["Red","White","White","Magenta","Yellow"] //gets the number of elements, set unordered, and non-repeating elementsprint (Setcolors,setcolors.count)//adding elementsSetcolors.insert ("Black") print (setcolors)//See if set contains red ifSetcolors.contains ("Red") {print ("There's something you want.") }Else{print ("Sorry, not yet added") } //Delete Element//Delete an elementSetcolors.remove ("Black") print (setcolors)//Delete all elementsSetcolors.removeall () print (setcolors)//define two setLet Numbers1:set = [1,2,3,4,5] Let Numbers2:set= [4,5,6,7,8,] //to traverse forNinchnumbers1 {print ("unordered: \ (n)") } forNinchnumbers1.sorted () {print ("ordered: \ (n)") } //operation between Set//find the same elements in the two setLet Newset =numbers1.intersection (numbers2). Sorted () print (Newset)//remove the same elements into a new collectionLet NewSet1 =numbers1.symmetricdifference (numbers2.sorted ()) print (NEWSET1)//merging two collectionsLet NewSet2 =numbers1.union (numbers2.sorted ()) print (NewSet2)//find elements not contained in the Numbers1 numbers2Let NewSet3 =numbers1.subtracting (numbers2.sorted ()) print (NEWSET3)//the relationship between collectionsLet a:set<int> = [1,2,3,4,5] Let B:set<Int> = [2,3,4] Let C:set<Int> = [4,5,6,7,8] Print ("whether the value of B is all contained in a", B.issubset (of:a)) print ("does a contain all the values of B", A.issuperset (of:b)) print ("A is a subset of B sets", A.isstrictsubset (of:b)) print ("whether A is a B parent set", A.isstrictsuperset (of:b)) print ("whether A and C do not intersect", A.isdisjoint (WITH:C))
Swift3.0 Set