I den här handledningen lär du dig vad ordlista är, skapar en ordbok och några vanliga funktioner i ordlistan.
I den tidigare artikeln om Swift Arrays lärde vi oss hur vi kan lagra flera värden i en variabel / konstant. I den här artikeln ska vi diskutera hur vi kan lagra data / värden som viktiga värdepar.
Vad är en ordbok?
En ordbok är helt enkelt en behållare som kan innehålla flera data som nyckel-värde-par på ett oordnat sätt.
Varje värde är associerat med en unik nyckel och lagrar data i oordnad lista från Sets, dvs du får inte elementen i samma ordning som du definierade objekten i ordboken.
Du kan använda ordlista istället för matris när du behöver leta upp värde med någon identifierare i samlingen. Antag att du kanske vill söka i huvudstaden i landet. I så fall skapar du en ordlista med nyckelland och huvudstad. Nu får du huvudstaden från samlingen genom att söka med nyckellandet.
Enkelt uttryckt parar du en nyckel till ett värde. I exemplet ovan parade vi ihop ett land med dess huvudstad.
Hur man förklarar en ordbok på Swift?
Du kan skapa en tom ordlista genom att ange key:value
datatypen inom parentes ()
.
Exempel 1: Förklara en tom ordbok
let emptyDic:(Int:String) = (:) print(emptyDic)
När du kör programmet blir resultatet:
(:)
ELLER
Du kan också definiera en tom ordbok enligt nedan:
let emptyDic:Dictionary = (:) print(emptyDic)
I ovanstående program har vi deklarerat en konstant tomDic av typordlista med nyckel av typ Int
och värde av typ String
och initierat den med 0-värden.
ELLER
Eftersom Swift är ett typsinferensspråk kan du också skapa ordlista direkt utan att specificera datatypen men måste initieras med vissa värden så att kompilatorn kan härleda sin typ som:
Exempel 2: Förklara en ordbok med vissa värden
let someDic = ("a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9) print(someDic)
När du kör programmet blir resultatet:
("b": 2, "a": 1, "i": 9, "c": 3, "e": 5, "f": 6, "g": 7, "d": 4, " h ": 8)
I ovanstående program har vi förklarat en ordlista utan att definiera typen uttryckligen men initialisera med några standardelement.
Elementet är i nyckel: värdepar där nyckel är av typ String
och värde är av Int
typ. Eftersom ordlistan är en oordnad lista print(someDic)
matar ut värdena i annan ordning än definierad.
Exempel 3: Skapa ordbok från två matriser
Vi kan också skapa en ordbok med hjälp av matriser.
let customKeys = ("Facebook", "Google", "Amazon") let customValues = ("Mark", "Larry", "Jeff") let newDictionary = Dictionary(uniqueKeysWithValues: zip(customKeys,customValues)) print(newDictionary)
När du kör programmet blir resultatet:
("Amazon": "Jeff", "Google": "Larry", "Facebook": "Mark")
I programmet ovan zip(customKeys,customValues)
skapar en ny sekvens av tuple med varje element som representerar värde från customKeys och customValues. Besök Swit zip om du vill lära dig mer om hur zip fungerar.
Nu kan vi skicka denna sekvens till Dictionary(uniqueKeysWithValues:)
initialiseraren och skapa en ny ordbok. Matar därför print(newDictionary)
ut en ny ordbok med element från två matriser.
Hur får jag tillgång till ordbokselement i Swift?
Som matriser kan du komma åt element i en ordlista med hjälp av syntax för prenumeration. Du måste inkludera nyckeln till det värde du vill komma åt inom hakparenteser direkt efter namnet på ordlistan.
Exempel 4: Åtkomst till element i en ordlista
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"))
När du kör programmet blir resultatet:
Tillval (1) Tillval (8)
Du kan också komma åt element i en ordlista med hjälp av in-loopar.
Exempel 5: Åtkomst till element i en ordlista med 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)") )
När du kör programmet blir resultatet:
tangent: b värde: 2 tangent: ett värde: 1 tangent: i värde: 9 tangent: c värde: 3 tangent: e värde: 5 tangent: f värde: 6 tangent: g värde: 7
Hur ändrar jag ordbokselement i Swift?
Du kan lägga till element i ordboken med hjälp av syntax för abonnemang. Du måste inkludera ny nyckel som abonnemangsindex och tilldela ett nytt värde av typen från ordbok.
Exempel 6: Ställa in element i en ordlista
var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") someDictionary("Japan") = "Tokyo" print(someDictionary)
När du kör programmet blir resultatet:
("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
I programmet ovan har vi angett ett värde Not Found i standardparametern när vi öppnade ordboken. Om värdet inte finns för nyckeln returneras standardvärdet annars returneras värdet.
I vårt fall är nyckeln "nepal" inte närvarande, så programmet returnerar Not Found .