Ebben az oktatóanyagban megtudhatja, mi is a szótár, létrehozhat egy szótárt és néhány általános műveletet a szótárban.
Az előző Swift Arrays cikkben megtudtuk, hogyan tárolhatunk több értéket egy változóban / konstansban. Ebben a cikkben megvitatjuk, hogyan tárolhatjuk az adatokat / értékeket kulcsértékpárként.
Mi a szótár?
A szótár egyszerűen egy olyan tároló, amely rendezetlenül több adatot tárolhat kulcs-érték párként.
Minden érték egyedi kulccsal van társítva, és az adatokat a Sets-től kezdve rendezetlen listában tárolja, vagyis nem az elemeket kapja meg ugyanabban a sorrendben, mint ahogy a szótárban megadta az elemeket.
Használhat szótárat tömb helyett, ha valamilyen azonosítóval kell keresnie az értéket a gyűjteményben. Tegyük fel, hogy érdemes keresni az ország fővárosában. Ebben az esetben létrehoz egy szótárat a legfontosabb országgal és a főváros értékével. Most kapja meg a fővárost a gyűjteményből, ha a kulcs országgal keres.
Egyszerűbben fogalmazva, párosít egy kulcsot egy értékhez. A fenti példában egy országot párosítottunk a fővárosával.
Hogyan lehet deklarálni a Swift szótárát?
Létrehozhat egy üres szótárt az key:value
Adattípus megadásával szögletes zárójelben ()
.
1. példa: Üres szótár deklarálása
let emptyDic:(Int:String) = (:) print(emptyDic)
A program futtatásakor a kimenet a következő lesz:
(:)
VAGY
Az alábbiakban definiálhat egy üres szótárat is:
let emptyDic:Dictionary = (:) print(emptyDic)
A fenti programban deklaráltunk egy konstans emptyDic of type szótárat típusú Int
és típusú típusú kulccsal, és String
0 értékkel inicializáltuk.
VAGY
Mivel a Swift egy típusú következtetési nyelv, szótárat is létrehozhat közvetlenül az Adattípus megadása nélkül, de néhány értékkel inicializálnia kell, hogy a fordító a következőképpen következtethessen a típusára:
2. példa: Szótár deklarálása néhány értékkel
let someDic = ("a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9) print(someDic)
A program futtatásakor a kimenet a következő lesz:
("b": 2, "a": 1, "i": 9, "c": 3, "e": 5, "f": 6, "g": 7, "d": 4 " h ": 8)
A fenti programban deklaráltunk egy szótárt anélkül, hogy a típust kifejezetten definiáltuk volna, hanem néhány alapértelmezett elemet inicializáltunk.
Az elem kulcs: érték pár, ahol a kulcs típusa String
és az értéke Int
típus. Mivel a szótár rendezetlen lista, print(someDic)
az értékeket a megadottól eltérő sorrendben adja ki.
3. példa: Szótár létrehozása két tömbből
Tömbök segítségével szótárt is létrehozhatunk.
let customKeys = ("Facebook", "Google", "Amazon") let customValues = ("Mark", "Larry", "Jeff") let newDictionary = Dictionary(uniqueKeysWithValues: zip(customKeys,customValues)) print(newDictionary)
A program futtatásakor a kimenet a következő lesz:
("Amazon": "Jeff", "Google": "Larry", "Facebook": "Mark")
A fenti programban zip(customKeys,customValues)
létrehoz egy új sorozat sorozatot az egyes elemekkel, amelyek a customKeys és a customValues értékét képviselik. Ha többet szeretne megtudni a zip működéséről, keresse fel a Swit zip oldalt.
Most átadhatjuk ezt a sorrendet az Dictionary(uniqueKeysWithValues:)
inicializálónak, és létrehozhatunk egy új Szótárat. Ezért print(newDictionary)
egy új Szótárat ad ki két tömb elemeivel.
How to access dictionary elements in Swift?
As arrays, you can access elements of a dictionary by using subscript syntax . You need to include key of the value you want to access within square brackets immediately after the name of the dictionary.
Example 4: Accessing elements of a dictionary
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"))
When you run the program, the output will be:
Optional(1) Optional(8)
You can also access elements of an dictionary using for-in loops.
Example 5: Accessing elements of an dictionary with for-in loop
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)") )
When you run the program, the output will be:
key:b value:2 key:a value:1 key:i value:9 key:c value:3 key:e value:5 key:f value:6 key:g value:7
How to modify dictionary elements in Swift?
You can add elements of in dictionary by using subscript syntax . You need to include new key as the subscript index and assign a new value of the type as of Dictionary.
Example 6: Setting elements in a dictionary
var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") someDictionary("Japan") = "Tokyo" print(someDictionary)
When you run the program, the output will be:
("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
A fenti programban az alapértelmezett paraméterben egy Nem található értéket adtunk meg a szótár elérése közben. Ha a kulcsnak nem létezik értéke, akkor az alapértelmezett értéket adja vissza, különben az értéket adja vissza.
Esetünkben a "Nepál" kulcs nincs jelen, ezért a program a Nem található értéket adja vissza .