Swift Sets: Kako ga uporabljati in zakaj? (Z primeri)

V tej vadnici boste izvedeli več o nizih, ustvarjanju, spreminjanju in nekaterih pogostih operacijah v nizih.

V prejšnjem članku Swift Arrays smo se naučili o ustvarjanju matrike, ki lahko vsebuje več vrednosti na urejenem seznamu.

Če pa moramo zagotoviti, da lahko seznam vsebuje vrednost samo enkrat, uporabimo niz v Swiftu.

Kaj je komplet?

Set je preprosto vsebnik, ki lahko vsebuje več vrednosti vrste podatkov na neurejenem seznamu in zagotavlja edinstven element v vsebniku (tj. Vsak podatek se prikaže samo enkrat).

Neurejeni seznam pomeni, da elementov ne boste dobili v enakem vrstnem redu, kot ste določili elemente v naboru.

Glavna prednost uporabe naborov nad nizi je, kadar morate zagotoviti, da se element pojavi samo enkrat in kadar vrstni red elementov ni pomemben.

Vrednosti, shranjene v naboru, morajo biti razpršljive . To pomeni, da mora zagotoviti lastnost hashValue. To je pomembno, ker so nabori neurejeni in uporablja hashValue, ki se uporablja za dostop do elementov naborov.

Vse osnovnih vrst SWIFT (na primer String, Int, Double, in Bool) so hashable privzeto, in se lahko uporablja kot vrste nastavljenih vrednosti. Vendar pa lahko v Swiftu ustvarite tudi svoj hashable type, ki ga lahko shranite v nabor.

Kako razglasiti niz v Swiftu?

Prazen nabor lahko ustvarite tako, da vrsto določite kot Set, ki ji sledi vrsta podatkov, v katere lahko shrani.

Primer 1: razglasitev praznega niza

 let emptyIntSet:Set = () print(emptyIntSet) 

ALI

 let emptyIntSet:Set = Set() print(emptyIntSet) 

Ko zaženete program, bo rezultat:

 ()

V zgornjem programu smo razglasili konstanto tipa emptyIntSet, Setki lahko shrani več vrednosti celih števil in inicializira z 0 vrednostmi.

Ker je Swift jezik za sklepanje o tipih, lahko tudi niz ustvarite neposredno, ne da bi določili vrsto podatkov, vendar ga morate inicializirati z nekaterimi vrednostmi, tako da lahko prevajalnik izbere svoj tip kot:

Primer 2: Deklaracija niza z nekaterimi vrednostmi

 let someIntSet:Set = (1, 2, 3, 4, 5, 6, 7, 8, 9) print(someIntSet) 

Ko zaženete program, bo rezultat:

 (2, 4, 9, 5, 6, 7, 3, 1, 8)

V zgornjem programu smo razglasili konstanto someIntSet, ki lahko hrani nabore Integer, ne da bi izrecno določila vrsto. Vendar moramo :Setpri definiranju spremenljivke pisati , sicer bo Swift ustvaril matriko za nas.

Prav tako smo kot nizi inicializirali niz z vrednostmi 1, 2, 3, 4, 5, 6, 7, 8, 9 z uporabo ()oklepajev.

Kot ste se naučili, ko boste poskušali vrednosti znotraj nabora natisniti kot print(someIntSet), boste rezultate dobili v drugačnem vrstnem redu, kot ste določili postavke v naboru, ker vsebuje vrednost brez definiranega vrstnega reda. Zato se vsakič, ko dostopate do vrstnega reda, spremeni.

3. primer: prijava niza s podvojenimi vrednostmi

 let someStrSet:Set = ("ab","bc","cd","de","ab") print(someStrSet) 

Ko zaženete program, bo rezultat:

 ("de", "ab", "cd", "bc")

V zgornjem programu smo v naboru definirali podvojeno vrednost ab . In. ko poskušamo dostopati do vrednosti znotraj nabora z uporabo print(someStrSet), se podvojena vrednost samodejno odstrani iz nabora. Zato set zagotavlja edinstvene elemente / vrednosti znotraj njega.

V Swiftu lahko deklarirate tudi niz z lastno vrsto Hashable Če želite izvedeti več, obiščite Swift Hashable.

Kako dostopati do nastavljenih elementov v Swiftu?

Do elementov nabora ne morete dostopati z uporabo sintakse podpisov kot nizov. To je zato, ker so nabori neurejeni in nimajo indeksov za dostop do elementov.

Torej, do nabora morate dostopati z uporabo njegovih metod in lastnosti ali z uporabo vhodnih zank.

Primer 4: Dostop do elementov niza

 var someStrSet:Set = ("ab", "bc", "cd", "de") for val in someStrSet ( print(val) ) 

Ko zaženete program, bo rezultat:

 de ab cd bc 

V zgornjem programu dobimo val v drugačnem vrstnem redu kot elementi nabora, ker so nabori za razliko od nizov neurejeni.

Do elementa nabora lahko dostopate tudi neposredno, tako da odstranite vrednost iz niza, kot je prikazano spodaj:

Primer 5: Dostop do elementov nabora z uporabo remove ()

 var someStrSet:Set = ("ab", "bc", "cd", "de") let someVal = someStrSet.remove("cd") print(someVal) print(someStrSet) 

Ko zaženete program, bo rezultat:

 Izbirno ("cd") ("de", "ab", "bc") 

V zgornjem programu lahko vidite, da metoda remove vrne neobvezen niz. Zato vam priporočamo, da ravnate neobvezno, kot je prikazano spodaj. Če želite izvedeti več o možnostih, obiščite Swift Optionals.

Primer 6: Neobvezno ravnanje z odstranjevanjem ()

 var someStrSet:Set = ("ab", "bc", "cd", "de") if let someVal = someStrSet.remove("cd") ( print(someVal) print(someStrSet) ) else ( print("cannot find element to remove") ) 

Ko zaženete program, bo rezultat:

 cd ("de", "ab", "bc") 

Kako dodati nov element v nabor?

Naboru lahko dodate nov element z uporabo insert()metode v Swiftu.

Primer 7: Dodajte nov element z uporabo insert ()

 var someStrSet:Set = ("ab", "bc", "cd", "de") someStrSet.insert("ef") print(someStrSet) 

Ko zaženete program, bo rezultat:

 ("ab", "de", "cd", "ef", "bc")

In the above program, we used the set's insert() method to add a new element to a set. Since, sets are unordered, the position of the inserted element isn't known.

Set Operations

Another main advantage of using Sets is you can perform set operations such as combining two sets together, determining which values two sets have in common etc. This operations are similar to the Set operation in Mathematics.

1. Union

The union of two sets a and b is the set of elements which are in a, or b, or in both a and b.

 let a: Set = (1, 3, 5, 7, 9) let b: Set = (0, 2, 4, 6, 8) print(a.union(b)) 

When you run the above program, the output will be:

 (8, 2, 9, 4, 5, 7, 6, 3, 1, 0)

2. Intersection

The intersection of two sets a and b is the set that contains all elements of a that also belong to b.

 let a: Set = (1, 3, 5, 7, 9) let b: Set = (0, 3, 7, 6, 8) print(a.intersection(b)) 

When you run the above program, the output will be:

 (7, 3)

Therefore, print(a.intersection(b)) outputs a new set with values (7, 3) that are common in both a and b.

3. Subtracting

The subtraction of two sets a and b is the set that contains all elements of a but removing the elements that also belong to b.

 let a: Set = (1, 3, 5, 7, 9) let b: Set = (0, 3, 7, 6, 8) print(a.subtracting(b)) 

When you run the above program, the output will be:

 (5, 9, 1)

Therefore, print(a.subtracting(b)) outputs a new set with values (5, 9, 1).

4. Symmetric Difference

The symmetric difference of two sets a and b is the set that contains all elements which are in either of the sets but not in both of them.

 let a: Set = (1, 3, 5, 7, 9) let b: Set = (0, 3, 7, 6, 8) print(a.symmetricDifference(b)) 

When you run the above program, the output will be:

 (5, 6, 8, 0, 1, 9)

Therefore, print(a.symmetricDifference(b)) outputs a new set with values (5, 6, 8, 0, 1, 9).

Set Membership and Equality Operations

Set Equality

You can use == operator to check whether two sets contains same elements or not. It returns true if two sets contains same elements otherwise returns false.

Example 5: Set equality operations

 let a: Set = (1, 3, 5, 7, 9) let b: Set = (0, 3, 7, 6, 8) let c:Set = (9, 7, 3, 1, 5) if a == b ( print("a and b are same") ) else ( print("a and b are different") ) if a == c ( print("a and c are same") ) else ( print("a and c are different") ) 

When you run the above program, the output will be:

 a and b are different a and c are same

Set membership

You can also check relationship between two sets using the following methods:

  • isSubset(of:)This method determines whether all of the values of a set are contained in the specified set.
  • isSuperset(of:) This method determines whether a set contains all of the values in a specified set
  • isStrictSubset(of:) or isStrictSuperset(of:): This method determines whether a set is a subset or superset, but not equal to, a specified set.
  • isDisjoint(with:) This method determines whether two sets have no values in common.

Example 6: Set membership operations

 let a: Set = (1, 3, 5, 7, 9) let b: Set = (0, 3, 1, 7, 6, 8, 9, 5) print("isSubset:", a.isSubset(of: b)) print("isSuperset:", b.isSuperset(of: a)) print("isStrictSubset:", a.isStrictSubset(of: b)) print("isDisjointWith:", a.isDisjoint(with: b)) 

When you run the above program,the output will be:

 isSubset: true isSuperset: true isStrictSubset: true isDisjointWith: false 

Let's analyze methods used inside the print statement below:

  • isSubsetreturns true because the set b contains all the elements in a
  • isSupersetreturn true because b contains all of the values of a.
  • isStrictSubsetreturns true because set b contains all the element in a and both sets are not equal.
  • isDisjointWithreturns false because a and b have some values in common.

Some helpful built in Set functions & properties

1. isEmpty

This property determines if a set is empty or not. It returns true if a set does not contain any value otherwise returns false.

Example 7: How isEmpty works?

 let intSet:Set = (21, 34, 54, 12) print(intSet.isEmpty) 

When you run the program, the output will be:

 false

2. first

This property is used to access first element of a set.

Example 8: How first works?

 let intSet = (21, 34, 54, 12) print(intSet.first) 

When you run the program, the output will be:

 Optional(54)

Since set is an unordered collection, the first property does not guarantee the first element of the set. You may get other value than 54.

Similarly, you can use last property to access last element of a set.

3. insert

The insert function is used to insert/append element in the set.

Example 9: How insert works?

 var intSet:Set = (21, 34, 54, 12) intSet.insert(50) print(intSet) 

When you run the program, the output will be:

 (54, 12, 50, 21, 34)

4. reversed

This function returns the elements of a set in reverse order.

Example 10: How reversed() works?

 var intSet:Set = (21, 22, 23, 24, 25) print(intSet) let reversedSet = intSet.reversed() print(reversedSet) 

When you run the program, the output will be:

 (22, 23, 21, 24, 25) (25, 24, 21, 23, 22) 

5. count

This property returns the total number of elements in a set.

Example 11: How count works?

 let floatSet:Set = (10.2, 21.3, 32.0, 41.3) print(floatSet.count) 

When you run the program, the output will be:

 4

6. removeFirst

This function removes and returns the first value from the set.

Example 12: How removeFirst works?

 var strSet:Set = ("ab", "bc", "cd", "de") let removedVal = strSet.removeFirst() print("removed value is (removedVal)") print(strSet) 

When you run the program, the output will be:

 removed value is de ("ab", "cd", "bc") 

Podobno lahko removeAllfunkcijo uporabite tudi za praznjenje nabora.

Zanimive Članki...