Schnelle Sets: Wie man es benutzt und warum? (Mit Beispielen)

In diesem Tutorial erfahren Sie mehr über Mengen, das Erstellen von Mengen, das Ändern dieser Mengen und einige allgemeine Operationen in Mengen.

Im vorherigen Artikel zu Swift Arrays haben wir gelernt, wie Sie ein Array erstellen, das mehrere Werte in einer geordneten Liste enthalten kann.

Wenn wir jedoch sicherstellen müssen, dass eine Liste nur einmal einen Wert enthalten kann, verwenden wir eine Menge in Swift.

Was ist ein Set?

Sets ist einfach ein Container, der mehrere Werte des Datentyps in einer ungeordneten Liste enthalten kann und ein eindeutiges Element im Container sicherstellt (dh, alle Daten werden nur einmal angezeigt).

Eine ungeordnete Liste bedeutet, dass Sie die Elemente nicht in derselben Reihenfolge erhalten, in der Sie die Elemente im Set definiert haben.

Der Hauptvorteil der Verwendung von Sets gegenüber Arrays besteht darin, dass Sie sicherstellen müssen, dass ein Element nur einmal angezeigt wird und die Reihenfolge der Elemente nicht wichtig ist.

In einem Satz gespeicherte Werte müssen hashbar sein . Dies bedeutet, dass eine hashValue-Eigenschaft bereitgestellt werden muss. Dies ist wichtig, da Mengen ungeordnet sind und hashValue verwendet wird, um auf die Elemente der Mengen zuzugreifen.

Alle Grundtypen von Swift (wie String, Int, Doubleund Bool) sind hashable standardmäßig und kann als Sollwerttyp verwendet werden. Sie können jedoch auch Ihren Hashable-Typ in Swift erstellen, der in einem Satz gespeichert werden kann.

Wie deklariere ich einen Satz in Swift?

Sie können einen leeren Satz erstellen, indem Sie den Typ als Satz gefolgt vom Datentyp angeben, in dem er gespeichert werden kann.

Beispiel 1: Deklarieren eines leeren Satzes

 let emptyIntSet:Set = () print(emptyIntSet) 

ODER

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

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

 ()

Im obigen Programm haben wir eine Konstante emptyIntSet vom Typ deklariert Set, die mehrere ganzzahlige Werte speichern und mit 0 Werten initialisieren kann.

Da Swift eine Typinferenzsprache ist, können Sie einen Satz auch direkt ohne Angabe des Datentyps erstellen, müssen ihn jedoch mit einigen Werten initialisieren, damit der Compiler auf seinen Typ schließen kann:

Beispiel 2: Deklarieren einer Menge mit einigen Werten

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

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

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

Im obigen Programm haben wir eine Konstante someIntSet deklariert, die Ganzzahlmengen speichern kann, ohne den Typ explizit anzugeben. Wir müssen jedoch schreiben, :Setwenn wir die Variable definieren, sonst erstellt Swift ein Array für uns.

Außerdem haben wir als Arrays den Satz mit 1, 2, 3, 4, 5, 6, 7, 8, 9 Werten in ()Klammern initialisiert .

Wie Sie gelernt haben, erhalten Sie beim Versuch, die Werte innerhalb des Satzes als zu drucken print(someIntSet), die Ergebnisse in einer anderen Reihenfolge als Sie die Elemente im Satz definiert haben, da darin Werte ohne definierte Reihenfolge gespeichert werden. Daher ändert sich jedes Mal, wenn Sie auf die Bestellung zugreifen.

Beispiel 3: Deklarieren eines Satzes mit doppelten Werten

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

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

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

Im obigen Programm haben wir einen doppelten Wert ab in der Menge definiert. Und. Wenn wir versuchen, mit auf den Wert innerhalb des Sets zuzugreifen print(someStrSet), wird der doppelte Wert automatisch aus dem Set entfernt. Daher garantiert set eindeutige Elemente / Werte darin.

Sie können in Swift auch einen Satz mit Ihrem eigenen benutzerdefinierten Hashable-Typ deklarieren. Um mehr zu erfahren, besuchen Sie Swift Hashable.

Wie greife ich in Swift auf Set-Elemente zu?

Sie können nicht auf Elemente eines Satzes zugreifen, indem Sie die tiefgestellte Syntax als Arrays verwenden. Dies liegt daran, dass Mengen ungeordnet sind und keine Indizes für den Zugriff auf die Elemente haben.

Sie müssen also mit ihren Methoden und Eigenschaften oder mit For-In-Schleifen auf das Set zugreifen.

Beispiel 4: Zugriff auf Elemente einer Menge

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

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

 de ab cd bc 

Im obigen Programm erhalten wir den Wert in einer anderen Reihenfolge als die Elemente einer Menge, da Mengen im Gegensatz zu Arrays ungeordnet sind.

Sie können auch direkt auf das Element eines Satzes zugreifen, indem Sie den Wert wie folgt aus dem Satz entfernen:

Beispiel 5: Zugriff auf Elemente einer Menge mit remove ()

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

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

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

Im obigen Programm können Sie sehen, dass die Methode remove eine optionale Zeichenfolge zurückgibt. Daher wird empfohlen, die optionale Behandlung wie folgt durchzuführen. Weitere Informationen zu Optionen finden Sie unter Swift Optionals.

Beispiel 6: Optionale Behandlung für 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") ) 

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

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

Wie füge ich ein neues Element zu einer Menge hinzu?

Sie können einem Set mithilfe der insert()Methode in Swift ein neues Element hinzufügen .

Beispiel 7: Neues Element mit insert () hinzufügen

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

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

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

In ähnlicher Weise können Sie auch die removeAllFunktion verwenden, um einen Satz zu leeren.

Interessante Beiträge...