Ātrā vārdnīca (ar piemēriem)

Šajā apmācībā jūs uzzināsiet, kas ir vārdnīca, izveidojot vārdnīcu un dažas parastās darbības vārdnīcā.

Iepriekšējā rakstā Swift Arrays mēs uzzinājām, kā mēs varam saglabāt vairākas vērtības mainīgajā / nemainīgajā. Šajā rakstā mēs apspriedīsim, kā mēs varam saglabāt datus / vērtības kā galveno vērtību pārus.

Kas ir vārdnīca?

Vārdnīca ir vienkārši konteiners, kurā var nesakārtoti glabāt vairākus datus kā atslēgu un vērtību pāri.

Katra vērtība ir saistīta ar unikālu atslēgu un glabā datus nesakārtotā sarakstā kopš kopas, ti, jūs nesaņemat elementus tādā pašā secībā, kā definējāt vienumus vārdnīcā.

Masīva vietā varat izmantot vārdnīcu, kad kolekcijā jāmeklē vērtība ar kādu identifikatoru. Pieņemsim, ka jūs varētu vēlēties meklēt valsts galvaspilsētu. Tādā gadījumā jūs izveidosiet vārdnīcu ar galveno valsti un vērtību galvaspilsētu. Tagad jūs iegūstat galvaspilsētu no kolekcijas, meklējot galveno valsti.

Vienkārši sakot, jūs pārī savienojat atslēgu ar vērtību. Iepriekš minētajā piemērā mēs savienojām valsti ar tās galvaspilsētu.

Kā pasludināt vārdnīcu Swift?

Jūs varat izveidot tukšu vārdnīcu, key:valuekvadrātiekavās norādot datu tipu ().

1. piemērs: tukšas vārdnīcas deklarēšana

 let emptyDic:(Int:String) = (:) print(emptyDic) 

Palaidot programmu, izeja būs:

 (:)

VAI

Varat arī definēt tukšu vārdnīcu šādi:

 let emptyDic:Dictionary = (:) print(emptyDic) 

Iepriekš minētajā programmā mēs esam deklarējuši konstantu tukšu Dic of type vārdnīcu ar tipa Intun tipa atslēgu Stringun inicializējuši to ar 0 vērtībām.

VAI

Tā kā Swift ir tipa secinājuma valoda, varat arī izveidot vārdnīcu tieši, nenorādot datu tipu, taču ir jāinicializē ar dažām vērtībām, lai kompilators varētu secināt tā veidu kā

2. piemērs: Vārdnīcas deklarēšana ar dažām vērtībām

 let someDic = ("a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9) print(someDic) 

Palaidot programmu, izeja būs:

 ("b": 2, "a": 1, "i": 9, "c": 3, "e": 5, "f": 6, "g": 7, "d": 4, " h ": 8)

Iepriekš minētajā programmā mēs esam deklarējuši vārdnīcu, skaidri nenosakot veidu, bet inicializējot ar dažiem noklusējuma elementiem.

Elements ir atslēgā: vērtību pāris, kur atslēga ir veida Stringun vērtība ir Intveida. Tā kā vārdnīca ir nesakārtots saraksts, print(someDic)vērtības tiek izvadītas atšķirīgā secībā, nekā noteikts.

3. piemērs: Vārdnīcas izveide no diviem masīviem

Mēs varam arī izveidot vārdnīcu, izmantojot masīvus.

 let customKeys = ("Facebook", "Google", "Amazon") let customValues = ("Mark", "Larry", "Jeff") let newDictionary = Dictionary(uniqueKeysWithValues: zip(customKeys,customValues)) print(newDictionary) 

Palaidot programmu, izeja būs:

 ("Amazon": "Jeff", "Google": "Larry", "Facebook": "Mark")

Iepriekš minētajā programmā zip(customKeys,customValues)tiek izveidota jauna virknes secība ar katru elementu, kas attēlo vērtību no customKeys un customValues. Lai uzzinātu vairāk par ZIP faila darbību, apmeklējiet vietni Swit zip.

Tagad mēs varam nodot šo secību Dictionary(uniqueKeysWithValues:)inicializatoram un izveidot jaunu vārdnīcu. Tāpēc print(newDictionary)izdod jaunu vārdnīcu ar elementiem no diviem masīviem.

Kā piekļūt vārdnīcas elementiem programmā Swift?

Kā masīvus jūs varat piekļūt vārdnīcas elementiem, izmantojot apakšraksta sintaksi. Tūlīt pēc vārdnīcas nosaukuma kvadrātiekavās jāiekļauj tās vērtības atslēga, kurai vēlaties piekļūt.

4. piemērs: Piekļuve vārdnīcas elementiem

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

Palaidot programmu, izeja būs:

 Izvēles (1) Izvēles (8) 

Varat arī piekļūt vārdnīcas elementiem, izmantojot ievadīšanas cilpas.

5. piemērs: Piekļuve vārdnīcas elementiem ar ievadīšanas cilpu

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

Palaidot programmu, izeja būs:

 atslēga: b vērtība: 2 atslēga: vērtība: 1 atslēga: i vērtība: 9 atslēga: c vērtība: 3 atslēga: e vērtība: 5 atslēga: f vērtība: 6 atslēga: g vērtība: 7 

Kā modificēt vārdnīcas elementus programmā Swift?

Vārdnīcā var pievienot elementus, izmantojot apakšteksta sintaksi. Jums jāiekļauj jauna atslēga kā indeksu indekss un jāpiešķir jauna veida vērtība kā vārdnīcā.

6. piemērs: elementu iestatīšana vārdnīcā

 var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") someDictionary("Japan") = "Tokyo" print(someDictionary) 

Palaidot programmu, izeja būs:

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

Iepriekš minētajā programmā, piekļūstot vārdnīcai, noklusējuma parametrā esam norādījuši vērtību Nav atrasta . Ja atslēgai nav vērtības, tiek atgriezta noklusējuma vērtība, pretējā gadījumā vērtība tiek atgriezta.

Mūsu gadījumā atslēgas "nepal" nav, tāpēc programma atgriež Not Found .

Interesanti raksti...