Seturi rapide: cum să îl utilizați și de ce? (Cu exemple)

În acest tutorial, veți afla despre seturi, crearea seturilor, modificarea acestora și câteva operații obișnuite în seturi.

În articolul anterior Swift Arrays, am aflat despre crearea unui tablou care poate conține mai multe valori într-o listă ordonată.

Dar, dacă trebuie să ne asigurăm că o listă poate deține o valoare o singură dată, vom folosi un set în Swift.

Ce este un set?

Seturi este pur și simplu un container care poate conține mai multe valori ale tipului de date într-o listă neordonată și asigură element unic în container (adică fiecare dată apare o singură dată).

Lista neordonată înseamnă că nu veți obține elementele în aceeași ordine în care ați definit articolele din set.

Principalul avantaj al utilizării seturilor peste matrice este atunci când trebuie să vă asigurați că un articol apare o singură dată și când ordinea articolelor nu este importantă.

Valorile stocate într-un set trebuie să fie hashable . Aceasta înseamnă că trebuie să furnizeze o proprietate hashValue. Acest lucru este important deoarece seturile sunt neordonate și folosește hashValue este utilizat pentru a accesa elementele seturilor.

Toate tipurile de bază Swift (cum ar fi String, Int, Doubleși Bool) sunt hashable în mod implicit, și poate fi folosit ca set tipuri de valoare. Cu toate acestea, puteți crea și tipul dvs. Hashable în Swift care poate fi stocat într-un set.

Cum să declarați un set în Swift?

Puteți crea un set gol specificând tipul ca set urmat de tipul de date în care poate fi stocat.

Exemplul 1: declararea unui set gol

 let emptyIntSet:Set = () print(emptyIntSet) 

SAU

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

Când rulați programul, ieșirea va fi:

 ()

În programul de mai sus, am declarat o constantă goalIntSet de tip Setcare poate stoca mai multe valori ale întregului și inițializată cu 0 valori.

Deoarece, Swift este un limbaj de inferență de tip, puteți crea, de asemenea, setul direct, fără a specifica tipul de date, dar trebuie să inițializați cu unele valori, astfel încât compilatorul să poată deduce tipul său ca:

Exemplul 2: declararea unui set cu unele valori

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

Când rulați programul, ieșirea va fi:

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

În programul de mai sus, am declarat o constantă someIntSet care poate stoca seturi de Integer fără a specifica în mod explicit tipul. Cu toate acestea, trebuie să scriem :Setatunci când definim variabila, altfel Swift va crea o matrice pentru noi.

De asemenea, ca tablouri, am inițializat setul cu valori 1, 2, 3, 4, 5, 6, 7, 8, 9 folosind ()parantezele.

După cum ați învățat, atunci când încercați să imprimați valorile din interiorul setului ca print(someIntSet), veți obține rezultatele într-o ordine diferită de cea pe care ați definit elementele din set, deoarece stochează valoare fără o comandă definită. Prin urmare, de fiecare dată când accesați comanda se modifică.

Exemplul 3: declararea unui set cu valori duplicat

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

Când rulați programul, ieșirea va fi:

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

În programul de mai sus, am definit o valoare duplicat ab în set. Și. când încercăm să accesăm valoarea din interiorul setului folosind print(someStrSet), valoarea duplicat este eliminată automat din set. Prin urmare, setul garantează elemente / valori unice în interiorul său.

De asemenea, puteți declara un set cu propriul tip Hashable personalizat în Swift. Pentru a afla mai multe, vizitați Swift Hashable.

Cum se accesează elementele setate în Swift?

Nu puteți accesa elemente ale unui set folosind sintaxa de indice ca tablouri. Acest lucru se datorează faptului că seturile sunt neordonate și nu au indici pentru a accesa elementele.

Deci, trebuie să accesați setul folosind metodele și proprietățile sale sau folosind bucle de intrare.

Exemplul 4: Accesarea elementelor unui set

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

Când rulați programul, ieșirea va fi:

 de ab cd bc 

În programul de mai sus, obținem valul în ordine diferită față de elementele unui set, deoarece seturile sunt neordonate spre deosebire de tablouri.

De asemenea, puteți accesa elementul unui set eliminând direct valoarea din set, după cum urmează:

Exemplul 5: accesarea elementelor unui set folosind remove ()

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

Când rulați programul, ieșirea va fi:

 Opțional („cd”) („de”, „ab”, „bc”) 

În programul de mai sus, puteți vedea că metoda de eliminare returnează un șir opțional. Prin urmare, vă recomandăm să faceți manipulări opționale, după cum urmează. Pentru a afla mai multe despre opționale, accesați opțiunile Swift.

Exemplul 6: Manevrare opțională pentru remove ()

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

Când rulați programul, ieșirea va fi:

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

Cum se adaugă un element nou într-un set?

Puteți adăuga un element nou la un set folosind insert()metoda din Swift.

Exemplul 7: Adăugați un element nou folosind insert ()

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

Când rulați programul, ieșirea va fi:

 ("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") 

În mod similar, puteți utiliza și removeAllfuncția pentru a goli un set.

Articole interesante...