Šioje pamokoje sužinosite apie rinkinius, rinkinių kūrimą, modifikavimą ir keletą bendrų rinkinių operacijų.
Ankstesniame straipsnyje „Swift Arrays“ sužinojome apie masyvo, kuris gali laikyti kelias reikšmes užsakytame sąraše, kūrimą.
Bet jei turime įsitikinti, kad sąraše reikšmė gali būti tik vieną kartą, „Swift“ naudojame rinkinį.
Kas yra rinkinys?
„Rinkiniai“ yra tiesiog talpykla, į kurią neįtrauktame sąraše telpa kelios duomenų tipo vertės ir užtikrinamas unikalus sudėtinio elemento elementas (t. Y. Visi duomenys rodomi tik vieną kartą).
Nesutvarkytas sąrašas reiškia, kad elementų negausite ta pačia tvarka, kaip apibrėžėte rinkinyje esančius elementus.
Pagrindinis rinkinių naudojimo, palyginti su masyvais, pranašumas yra tas, kai reikia įsitikinti, kad elementas rodomas tik vieną kartą ir kai elementų tvarka nėra svarbi.
Rinkinyje saugomos vertės turi būti maišos . Tai reiškia, kad ji turi pateikti ypatybę hashValue. Tai svarbu, nes rinkiniai nėra sutvarkyti ir norint pasiekti rinkinių elementus, naudojama hashValue.
Visi SWIFT pagrindinių tipų (pvz String
, Int
, Double
, ir Bool
) yra hashable pagal nutylėjimą, ir gali būti naudojamas kaip nustatyta vertė tipų. Tačiau „Swift“ galite sukurti ir „Hashable Type“, kurį galima laikyti rinkinyje.
Kaip paskelbti rinkinį „Swift“?
Galite sukurti tuščią rinkinį nurodydami tipą „Rinkinys“, po kurio nurodomas duomenų tipas, kurį jis gali laikyti.
1 pavyzdys: tuščio rinkinio deklaravimas
let emptyIntSet:Set = () print(emptyIntSet)
ARBA
let emptyIntSet:Set = Set() print(emptyIntSet)
Kai paleisite programą, išvestis bus:
()
Pirmiau pateiktoje programoje mes paskelbėme pastovią tipo tyhjIntSet, Set
kuris gali išsaugoti kelias sveikojo skaičiaus reikšmes ir inicijuoti 0 reikšmėmis.
Kadangi „Swift“ yra tipo išvadų kalba, taip pat galite sukurti rinkinį tiesiogiai nenurodydami duomenų tipo, tačiau turite inicijuoti kai kurias reikšmes, kad kompiliatorius galėtų padaryti išvadą apie jo tipą:
2 pavyzdys: aibės su kai kuriomis reikšmėmis deklaravimas
let someIntSet:Set = (1, 2, 3, 4, 5, 6, 7, 8, 9) print(someIntSet)
Kai paleisite programą, išvestis bus:
(2, 4, 9, 5, 6, 7, 3, 1, 8)
Pirmiau pateiktoje programoje mes paskelbėme pastovią „someIntSet“, galintį išsaugoti sveikojo skaičiaus rinkinius, aiškiai nenurodydami tipo. Tačiau mes turime parašyti :Set
apibrėždami kintamąjį, kitaip „Swift“ sukurs mums masyvą.
Be to, kaip masyvai, mes inicializavome rinkinį su 1, 2, 3, 4, 5, 6, 7, 8, 9 reikšmėmis, naudodami ()
skliaustus.
Kaip sužinojote, bandydami atspausdinti reikšmes rinkinio viduje print(someIntSet)
, rezultatus gausite kita tvarka, nei apibrėžėte rinkinio elementus, nes jame saugoma vertė be apibrėžto eiliškumo. Todėl kiekvieną kartą, kai pasiekiate užsakymą, pasikeičia.
3 pavyzdys: aibės su pasikartojančiomis reikšmėmis deklaravimas
let someStrSet:Set = ("ab","bc","cd","de","ab") print(someStrSet)
Kai paleisite programą, išvestis bus:
(„de“, „ab“, „cd“, „bc“)
Pirmiau pateiktoje programoje mes rinkinyje apibrėžėme dublikato reikšmę ab . Ir. kai bandome pasiekti reikšmę rinkinio viduje naudodami print(someStrSet)
, pasikartojanti vertė automatiškai pašalinama iš rinkinio. Todėl rinkinys garantuoja unikalius elementus / vertybes jo viduje.
Be to, „Swift“ galite deklaruoti rinkinį naudodami savo pasirinktą „Hashable“ tipą. Norėdami sužinoti daugiau, apsilankykite „Swift Hashable“.
Kaip pasiekti nustatytus elementus „Swift“?
Negalite pasiekti rinkinio elementų naudodami indeksų sintaksę kaip masyvus. Taip yra todėl, kad rinkiniai nėra sutvarkyti ir neturi indeksų, kad būtų galima pasiekti elementus.
Taigi, jūs turite pasiekti rinkinį naudodami jo metodus ir ypatybes arba naudodami „for-in“ kilpas.
4 pavyzdys: Prieiga prie rinkinio elementų
var someStrSet:Set = ("ab", "bc", "cd", "de") for val in someStrSet ( print(val) )
Kai paleisite programą, išvestis bus:
de ab cd bc
Pirmiau pateiktoje programoje mes gauname val skirtinga tvarka nei aibės elementai, nes aibės yra nesutvarkytos, skirtingai nuo masyvų.
Taip pat galite prieiti prie rinkinio elemento, tiesiogiai pašalindami vertę iš rinkinio, kaip nurodyta toliau:
5 pavyzdys: Prieiga prie rinkinio elementų naudojant šalinimo ()
var someStrSet:Set = ("ab", "bc", "cd", "de") let someVal = someStrSet.remove("cd") print(someVal) print(someStrSet)
Kai paleisite programą, išvestis bus:
Neprivaloma („cd“) („de“, „ab“, „bc“)
Pirmiau pateiktoje programoje galite pamatyti, kad pašalinimo metodas pateikia pasirinktinę eilutę. Todėl rekomenduojama atlikti papildomą tvarkymą, kaip nurodyta toliau. Norėdami sužinoti daugiau apie papildomus variantus, apsilankykite „Swift Optionals“.
6 pavyzdys: Pasirenkamas „Remove“ () tvarkymas
var someStrSet:Set = ("ab", "bc", "cd", "de") if let someVal = someStrSet.remove("cd") ( print(someVal) print(someStrSet) ) else ( print("cannot find element to remove") )
Kai paleisite programą, išvestis bus:
CD („de“, „ab“, „bc“)
Kaip pridėti naują elementą rinkinyje?
Naudodami insert()
„Swift“ metodą, galite pridėti naują elementą prie rinkinio .
7 pavyzdys: pridėkite naują elementą naudodami insert ()
var someStrSet:Set = ("ab", "bc", "cd", "de") someStrSet.insert("ef") print(someStrSet)
Kai paleisite programą, išvestis bus:
("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 setisStrictSubset(of:
) orisStrictSuperset(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:
isSubset
returnstrue
because the set b contains all the elements in aisSuperset
returntrue
because b contains all of the values of a.isStrictSubset
returnstrue
because set b contains all the element in a and both sets are not equal.isDisjointWith
returnsfalse
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")
Panašiai removeAll
funkciją galite naudoti ir rinkiniui ištuštinti.