În acest tutorial, veți afla despre ce este dicționarul, crearea unui dicționar și câteva operații obișnuite în dicționar.
În articolul anterior Swift Arrays, am aflat cum putem stoca mai multe valori într-o variabilă / constantă. În acest articol, vom discuta despre modul în care putem stoca date / valori ca perechi de valori cheie.
Ce este un dicționar?
Un dicționar este pur și simplu un container care poate conține mai multe date ca pereche cheie-valoare într-un mod neordonat.
Fiecare valoare este asociată cu o cheie unică și stochează date într-o listă neordonată din seturi, adică nu primiți elementele în aceeași ordine în care ați definit articolele din dicționar.
Puteți utiliza dicționar în loc de matrice atunci când trebuie să căutați valoare cu un anumit identificator din colecție. Să presupunem că poate doriți să căutați în capitala țării. În acest caz, veți crea un dicționar cu țara cheie și capitala valorică. Acum, veți obține capitala din colecție căutând cu țara cheie.
În termeni simpli, asociați o cheie cu o valoare. În exemplul de mai sus, am asociat o țară cu capitala sa.
Cum să declarați un dicționar în Swift?
Puteți crea un dicționar gol, specificând key:value
tipul de date între paranteze drepte ()
.
Exemplul 1: declararea unui dicționar gol
let emptyDic:(Int:String) = (:) print(emptyDic)
Când rulați programul, ieșirea va fi:
(:)
SAU
De asemenea, puteți defini un dicționar gol după cum urmează:
let emptyDic:Dictionary = (:) print(emptyDic)
În programul de mai sus, am declarat o dicție constantă goală de dicționar de tip cu cheie de tip Int
și valoare de tip String
și l-am inițializat cu 0 valori.
SAU
Deoarece Swift este un limbaj de inferență de tip, puteți crea, de asemenea, dicționar 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 dicționar cu unele valori
let someDic = ("a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9) print(someDic)
Când rulați programul, ieșirea va fi:
("b": 2, "a": 1, "i": 9, "c": 3, "e": 5, "f": 6, "g": 7, "d": 4, " h ": 8)
În programul de mai sus, am declarat un dicționar fără a defini în mod explicit tipul, dar inițializând cu unele elemente implicite.
Elementul este în pereche cheie: valoare unde cheia este de tip String
și valoarea este de Int
tip. Deoarece dicționarul este o listă neordonată, print(someDic)
rezultatele valorilor sunt diferite în ordinea definită.
Exemplul 3: Crearea dicționarului din două matrice
De asemenea, putem crea un dicționar folosind tablouri.
let customKeys = ("Facebook", "Google", "Amazon") let customValues = ("Mark", "Larry", "Jeff") let newDictionary = Dictionary(uniqueKeysWithValues: zip(customKeys,customValues)) print(newDictionary)
Când rulați programul, ieșirea va fi:
(„Amazon”: „Jeff”, „Google”: „Larry”, „Facebook”: „Mark”)
În programul de mai sus, zip(customKeys,customValues)
creează o nouă secvență de tupluri cu fiecare element reprezentând valoarea din customKeys și customValues. Pentru a afla mai multe despre cum funcționează zip, vizitați Swit zip.
Acum, putem trece această secvență Dictionary(uniqueKeysWithValues:)
inițializatorului și putem crea un nou dicționar. Prin urmare, print(newDictionary)
scoate un nou dicționar cu elemente din două matrice.
Cum se accesează elementele dicționarului în Swift?
Ca tablouri, puteți accesa elementele unui dicționar utilizând sintaxa subscriptului. Trebuie să includeți cheia valorii pe care doriți să o accesați între paranteze pătrate imediat după numele dicționarului.
Exemplul 4: accesarea elementelor unui dicționar
let someDic = ("a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9) print(someDic("a")) print(someDic("h"))
Când rulați programul, ieșirea va fi:
Opțional (1) Opțional (8)
De asemenea, puteți accesa elemente ale unui dicționar folosind bucle for-in.
Exemplul 5: accesarea elementelor unui dicționar cu buclă for-in
let someDic = ("a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9) for (key,value) in someDic ( print("key:(key) value:(value)") )
Când rulați programul, ieșirea va fi:
cheie: valoare b: 2 cheie: o valoare: 1 cheie: valoare i: 9 cheie: valoare c: 3 cheie: valoare e: 5 cheie: valoare f: 6 cheie: valoare g: 7
Cum se modifică elementele dicționarului în Swift?
Puteți adăuga elemente din dicționar folosind sintaxa subscriptului. Trebuie să includeți o nouă cheie ca index de indice și să atribuiți o nouă valoare de tip din Dicționar.
Exemplul 6: Setarea elementelor într-un dicționar
var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") someDictionary("Japan") = "Tokyo" print(someDictionary)
Când rulați programul, ieșirea va fi:
("Japan": "Tokyo", "China": "Beijing", "India": "NewDelhi", "Nepal": "Kathmandu")
In the above example, we've created a new key-value pair "Japan": "Tokyo"
in the given dictionary by using the subscript syntax.
You can also use subscript syntax to change the value associated with a particular key as:
Example 7: Changing elements of a dictionary
var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") someDictionary("Nepal") = "KATHMANDU" print(someDictionary)
When you run the program, the output will be:
("China": "Beijing", "India": "NewDelhi", "Nepal": "KATHMANDU")
Some helpful built-in Dictionary functions & properties
1. isEmpty
This property determines if an dictionary is empty or not. It returns true
if a dictionary does not contain any value otherwise returns false
.
Example 8: How isEmpty works?
let someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") print(someDictionary.isEmpty)
When you run the program, the output will be:
false
2. first
This property is used to access the first element of a dictionary.
Example 9: How first works?
let someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") print(someDictionary.first)
When you run the program, the output will be:
Optional((key: "China", value: "Beijing"))
3. count
This property returns the total number of elements (key-value pair) in a dictionary.
Example 10: How count works?
let someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") print(someDictionary.count)
When you run the program, the output will be:
3
4. keys
This property returns all the keys inside the dictionary.
Example 11: How keys works?
var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") let dictKeys = Array(someDictionary.keys) print(dictKeys)
When you run the program, the output will be:
("China", "India", "Nepal")
Similarly, you can use values to get all the values inside the dictionary.
5. removeValue
This function removes and returns the value specified with the key from the dictionary. Both key value pair will be removed from the dictionary.
Example 12: How removeValue() works?
var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") let val = someDictionary.removeValue(forKey: "Nepal") print(val) print(someDictionary)
When you run the program, the output will be:
Optional("Kathmandu") ("India": "NewDelhi", "China": "Beijing")
Similarly, you can also use removeAll function to empty an dictionary.
Things to Remember
1. While using subscript syntax to access elements of an dictionary in Swift, you must be sure the key lies in the index otherwise you will get a nil value. Let's see this in example:
Example 13: Key must be present
var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") let val = someDictionary("Japan") print(val)
When you run the program, the output will be:
nil
In the above program, there is no key Japan. So when you try to access the value of the key "Japan", you will get a nil
value.
2. Likewise, key-values are case-sensitive in Swift, so you must make sure the correct cased key/value is used. Otherwise, you will get a nil
value. Let's see this in example:
Example 14: Keys are case-sensitive
var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") let val = someDictionary("nepal") print(val)
When you run the program, the output will be:
nil
In the above program, there is no key nepal. So when you try to access the value of the key "nepal", you will get a nil
value.
3. There is also a way to provide a default value if the value for a given key does not exist. Let's see this in example:
Example 12: Default value for non-existent key
var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") let val = someDictionary("nepal", default:"Not Found") print(val)
When you run the program, the output will be:
Not Found
În programul de mai sus, am specificat o valoare Not Found în parametrul implicit la accesarea dicționarului. Dacă valoarea nu există pentru cheie, valoarea implicită este returnată altfel se returnează valoarea.
În cazul nostru, cheia „nepal” nu este prezentă, așa că programul returnează Not Found .