Swift Sets: come usarlo e perché? (Con esempi)

In questo tutorial imparerai a conoscere i set, la creazione di set, la loro modifica e alcune operazioni comuni nei set.

Nel precedente articolo di Swift Arrays, abbiamo imparato a creare un array che può contenere più valori in un elenco ordinato.

Ma, se dobbiamo assicurarci che un elenco possa contenere un valore solo una volta, utilizziamo un set in Swift.

Cos'è un set?

Sets è semplicemente un contenitore che può contenere più valori di tipo di dati in un elenco non ordinato e garantisce un elemento univoco nel contenitore (cioè ogni dato appare solo una volta).

L'elenco non ordinato significa che non otterrai gli elementi nello stesso ordine in cui hai definito gli elementi nel set.

Il vantaggio principale dell'utilizzo di set su array è quando è necessario assicurarsi che un elemento venga visualizzato solo una volta e quando l'ordine degli elementi non è importante.

I valori memorizzati in un set devono essere modificabili . Ciò significa che deve fornire una proprietà hashValue. Questo è importante perché gli insiemi non sono ordinati e utilizza hashValue per accedere agli elementi degli insiemi.

Tutti i tipi di base di Swift (come String, Int, Double, e Bool) sono hashable per impostazione predefinita e può essere utilizzato come tipi valore impostato. Tuttavia, puoi anche creare il tuo tipo Hashable in Swift che può essere memorizzato in un set.

Come dichiarare un set in Swift?

È possibile creare un set vuoto specificando il tipo come Set seguito dal tipo di dati in cui è possibile memorizzare.

Esempio 1: dichiarazione di un set vuoto

 let emptyIntSet:Set = () print(emptyIntSet) 

O

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

Quando esegui il programma, l'output sarà:

 ()

Nel programma sopra, abbiamo dichiarato una costante emptyIntSet di tipo Setche può memorizzare più valori di intero e inizializzata con valori 0.

Poiché Swift è un linguaggio di inferenza del tipo, puoi anche creare un set direttamente senza specificare il tipo di dati ma deve essere inizializzato con alcuni valori in modo che il compilatore possa dedurre il suo tipo come:

Esempio 2: dichiarazione di un insieme con alcuni valori

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

Quando esegui il programma, l'output sarà:

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

Nel programma sopra, abbiamo dichiarato una costante someIntSet che può memorizzare set di Integer senza specificare esplicitamente il tipo. Tuttavia, dobbiamo scrivere :Setquando definiamo la variabile, altrimenti Swift creerà un array per noi.

Inoltre, come array, abbiamo inizializzato il set con 1, 2, 3, 4, 5, 6, 7, 8, 9 valori utilizzando le ()parentesi.

Come hai imparato, quando provi a stampare i valori all'interno del set come print(someIntSet), otterrai i risultati in un ordine diverso da quello che hai definito gli articoli nel set perché memorizza il valore senza un ordine definito. Pertanto, ogni volta che accedi all'ordine cambia.

Esempio 3: dichiarazione di un insieme con valori duplicati

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

Quando esegui il programma, l'output sarà:

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

Nel programma precedente, abbiamo definito un valore duplicato ab nell'insieme. E. quando proviamo ad accedere al valore all'interno del set utilizzando print(someStrSet), il valore duplicato viene automaticamente rimosso dal set. Pertanto, set garantisce elementi / valori univoci al suo interno.

Puoi anche dichiarare un set con il tuo tipo Hashable personalizzato in Swift. Per saperne di più, visita Swift Hashable.

Come accedere agli elementi del set in Swift?

Non è possibile accedere agli elementi di un insieme utilizzando la sintassi del pedice come array. Questo perché gli insiemi non sono ordinati e non hanno indici per accedere agli elementi.

Quindi, è necessario accedere al set utilizzando i suoi metodi e proprietà o utilizzando i cicli for-in.

Esempio 4: accesso agli elementi di un set

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

Quando esegui il programma, l'output sarà:

 de ab cd bc 

Nel programma precedente, otteniamo val in un ordine diverso rispetto agli elementi di un insieme perché gli insiemi non sono ordinati a differenza degli array.

Puoi anche accedere a un elemento di un set rimuovendo direttamente il valore dal set come di seguito:

Esempio 5: accesso agli elementi di un set utilizzando remove ()

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

Quando esegui il programma, l'output sarà:

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

Nel programma sopra, puoi vedere che il metodo remove restituisce una stringa opzionale. Pertanto, si consiglia di eseguire la gestione opzionale come di seguito. Per saperne di più sugli optional, visita Swift Optionals.

Esempio 6: gestione facoltativa per 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") ) 

Quando esegui il programma, l'output sarà:

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

Come aggiungere un nuovo elemento in un set?

Puoi aggiungere un nuovo elemento a un set utilizzando il insert()metodo in Swift.

Esempio 7: aggiungere un nuovo elemento utilizzando insert ()

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

Quando esegui il programma, l'output sarà:

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

Nel programma sopra, abbiamo usato il insert()metodo del set per aggiungere un nuovo elemento a un set. Poiché gli insiemi non sono ordinati, la posizione dell'elemento inserito non è nota.

Imposta operazioni

Un altro vantaggio principale dell'utilizzo degli insiemi è che puoi eseguire operazioni sugli insiemi come combinare due insiemi insieme, determinare quali valori hanno in comune due insiemi, ecc. Queste operazioni sono simili all'operazione Insiemi in Matematica.

1. Unione

L'unione di due insiemi a e b è l'insieme di elementi che sono in a, o b, o in entrambi a e b.

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

Quando esegui il programma sopra, l'output sarà:

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

2. Intersezione

L'intersezione di due insiemi aeb è l'insieme che contiene tutti gli elementi di a che appartengono anche a b.

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

Quando esegui il programma sopra, l'output sarà:

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

Allo stesso modo, puoi anche usare la removeAllfunzione per svuotare un set.

Articoli interessanti...