Šioje pamokoje sužinosite, kas yra žodynas, kurdami žodyną ir keletą bendrų žodyno operacijų.
Ankstesniame straipsnyje „Swift Arrays“ sužinojome, kaip galime išsaugoti kelias reikšmes kintamajame / konstantoje. Šiame straipsnyje aptarsime, kaip duomenis / vertes galime laikyti kaip pagrindinių reikšmių poras.
Kas yra žodynas?
Žodynas yra tiesiog talpykla, kurioje galima sutvarkyti kelis duomenis kaip rakto ir vertės porą netvarkingai.
Kiekviena reikšmė yra susieta su unikaliu raktu ir kaupia duomenis nesutvarkytame sąraše nuo rinkinių, ty jūs negaunate elementų tokia pačia tvarka, kaip apibrėžėte elementus žodyne.
Galite naudoti žodyną vietoj masyvo, kai jums reikia ieškoti vertės su tam tikru identifikatoriumi kolekcijoje. Tarkime, galbūt norėsite ieškoti šalies sostinėje. Tokiu atveju sukursite žodyną su pagrindine šalimi ir vertinga sostine. Dabar gausite sostinę iš kolekcijos ieškodami pagrindinės šalies.
Paprasčiau tariant, jūs susiejate raktą su verte. Ankstesniame pavyzdyje mes suporavome šalį su jos sostine.
Kaip paskelbti žodyną „Swift“?
Tuščią žodyną galite sukurti nurodydami key:value
duomenų tipą laužtiniuose skliaustuose ()
.
1 pavyzdys: tuščio žodyno deklaravimas
let emptyDic:(Int:String) = (:) print(emptyDic)
Kai paleisite programą, išvestis bus:
(:)
ARBA
Taip pat galite apibrėžti tuščią žodyną taip:
let emptyDic:Dictionary = (:) print(emptyDic)
Pirmiau pateiktoje programoje mes paskelbėme pastovų tuščią tipo žodyną su tipo Int
ir tipo rakto raktu String
ir inicijavome jį 0 reikšmėmis.
ARBA
Kadangi „Swift“ yra tipo išvadų kalba, taip pat galite tiesiogiai sukurti žodyną nenurodydami duomenų tipo, tačiau turite inicijuoti kai kurias reikšmes, kad kompiliatorius galėtų padaryti išvadą apie savo tipą:
2 pavyzdys: žodyno su kai kuriomis reikšmėmis deklaravimas
let someDic = ("a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9) print(someDic)
Kai paleisite programą, išvestis bus:
(„b“: 2, „a“: 1, „i“: 9, „c“: 3, „e“: 5, „f“: 6, „g“: 7, „d“: 4, " h ": 8)
Pirmiau pateiktoje programoje mes paskelbėme žodyną, aiškiai neapibrėždami tipo, bet inicijuodami kai kuriuos numatytuosius elementus.
Elementas yra raktas: vertės pora, kur raktas yra tipo, String
o vertė - Int
tipo. Kadangi žodynas yra nesutvarkytas sąrašas print(someDic)
, vertės pateikiamos kita tvarka, nei nustatyta.
3 pavyzdys: žodyno kūrimas iš dviejų masyvų
Mes taip pat galime sukurti žodyną naudodami masyvus.
let customKeys = ("Facebook", "Google", "Amazon") let customValues = ("Mark", "Larry", "Jeff") let newDictionary = Dictionary(uniqueKeysWithValues: zip(customKeys,customValues)) print(newDictionary)
Kai paleisite programą, išvestis bus:
(„Amazon“: „Jeff“, „Google“: „Larry“, „Facebook“: „Mark“)
Pirmiau pateiktoje programoje zip(customKeys,customValues)
sukuriama nauja eilės eilutė su kiekvienu elementu, nurodančiu „customKeys“ ir „customValues“ vertę. Norėdami sužinoti daugiau apie tai, kaip veikia „ZIP“, apsilankykite „Swit zip“.
Dabar mes galime perduoti šią seką Dictionary(uniqueKeysWithValues:)
iniciatoriui ir sukurti naują žodyną. Todėl print(newDictionary)
išleidžia naują žodyną su elementais iš dviejų masyvų.
Kaip pasiekti „Swift“ žodyno elementus?
Kaip masyvus galite pasiekti žodyno elementus naudodami indekso sintaksę. Iš karto po žodyno pavadinimo kvadratiniuose skliaustuose turite įtraukti vertės, kurią norite pasiekti, raktą.
4 pavyzdys: Prieiga prie žodyno elementų
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"))
Kai paleisite programą, išvestis bus:
Pasirenkama (1) Pasirenkama (8)
Žodyno elementus taip pat galite pasiekti naudodami įvesties kilpas.
5 pavyzdys: Prieiga prie žodyno elementų su įvesties kilpa
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)") )
Kai paleisite programą, išvestis bus:
raktas: b reikšmė: 2 raktas: reikšmė: 1 raktas: i reikšmė: 9 raktas: c reikšmė: 3 raktas: e reikšmė: 5 raktas: f reikšmė: 6 raktas: g vertė: 7
Kaip modifikuoti „Swift“ žodyno elementus?
Žodyne galite pridėti elementų naudodami indekso sintaksę. Kaip prenumeratos indeksą turite įtraukti naują raktą ir priskirti naują tipo žodžio reikšmę.
6 pavyzdys: elementų nustatymas žodyne
var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") someDictionary("Japan") = "Tokyo" print(someDictionary)
Kai paleisite programą, išvestis bus:
("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
Pirmiau pateiktoje programoje, norėdami patekti į žodyną, numatytame parametre nurodėme reikšmę Nerasta . Jei rakto reikšmė neegzistuoja, grąžinama numatytoji vertė, kitaip ji grąžinama.
Mūsų atveju rakto „nepal“ nėra, todėl programa pateikia „ Not Found“ .