Dizionario rapido (con esempi)

In questo tutorial imparerai cos'è il dizionario, creando un dizionario e alcune operazioni comuni nel dizionario.

Nel precedente articolo di Swift Arrays, abbiamo imparato come memorizzare più valori in una variabile / costante. In questo articolo, discuteremo di come memorizzare dati / valori come coppie di valori chiave.

Cos'è un dizionario?

Un dizionario è semplicemente un contenitore che può contenere più dati come coppia chiave-valore in modo non ordinato.

Ogni valore è associato a una chiave univoca e memorizza i dati in una lista non ordinata a partire da Sets, ovvero non ottieni gli elementi nello stesso ordine in cui hai definito gli elementi nel dizionario.

È possibile utilizzare il dizionario anziché l'array quando è necessario cercare un valore con un identificatore nella raccolta. Supponi di voler cercare nella capitale del paese. In tal caso, creerai un dizionario con il paese chiave e il valore capitale. Ora ottieni la capitale dalla raccolta cercando con il paese chiave.

In termini semplici, abbini una chiave a un valore. Nell'esempio sopra, abbiamo abbinato un paese alla sua capitale.

Come dichiarare un dizionario in Swift?

È possibile creare un dizionario vuoto specificando il key:valuetipo di dati tra parentesi quadre ().

Esempio 1: dichiarazione di un dizionario vuoto

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

Quando esegui il programma, l'output sarà:

 (:)

O

Puoi anche definire un dizionario vuoto come di seguito:

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

Nel programma precedente, abbiamo dichiarato una costante emptyDic di tipo dizionario con chiave di tipo Inte valore di tipo Stringe inizializzata con valori 0.

O

Poiché Swift è un linguaggio di inferenza del tipo, puoi anche creare un dizionario direttamente senza specificare il tipo di dati ma deve essere inizializzato con alcuni valori in modo che il compilatore possa dedurre il suo tipo come:

Esempio 2: dichiarazione di un dizionario con alcuni valori

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

Quando esegui il programma, l'output sarà:

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

Nel programma precedente, abbiamo dichiarato un dizionario senza definire esplicitamente il tipo ma inizializzandolo con alcuni elementi predefiniti.

L'elemento è nella coppia chiave: valore dove la chiave è di tipo Stringe il valore è di Inttipo. Poiché il dizionario è un elenco non ordinato, print(someDic)restituisce i valori in un ordine diverso da quello definito.

Esempio 3: creazione di un dizionario da due array

Possiamo anche creare un dizionario usando gli array.

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

Quando esegui il programma, l'output sarà:

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

Nel programma precedente, zip(customKeys,customValues)crea una nuova sequenza di tupla con ogni elemento che rappresenta il valore da customKeys e customValues. Per saperne di più su come funziona zip, visita Swit zip.

Ora possiamo passare questa sequenza Dictionary(uniqueKeysWithValues:)all'inizializzatore e creare un nuovo Dictionary. Pertanto, print(newDictionary)restituisce un nuovo dizionario con elementi da due array.

Come accedere agli elementi del dizionario in Swift?

Come array, puoi accedere agli elementi di un dizionario usando la sintassi del pedice. È necessario includere la chiave del valore a cui si desidera accedere tra parentesi quadre immediatamente dopo il nome del dizionario.

Esempio 4: accesso agli elementi di un dizionario

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

Quando esegui il programma, l'output sarà:

 Opzionale (1) Opzionale (8) 

È inoltre possibile accedere agli elementi di un dizionario utilizzando i cicli for-in.

Esempio 5: accesso agli elementi di un dizionario con ciclo 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)") ) 

Quando esegui il programma, l'output sarà:

 chiave: valore b: 2 chiave: valore a: 1 chiave: valore i: 9 chiave: valore c: 3 chiave: valore e: 5 chiave: valore f: 6 chiave: valore g: 7 

Come modificare gli elementi del dizionario in Swift?

Puoi aggiungere elementi di nel dizionario usando la sintassi del pedice. È necessario includere una nuova chiave come indice pedice e assegnare un nuovo valore del tipo a partire da Dictionary.

Esempio 6: impostazione di elementi in un dizionario

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

Quando esegui il programma, l'output sarà:

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

Nel programma precedente, abbiamo specificato un valore Non trovato nel parametro predefinito durante l'accesso al dizionario. Se il valore non esiste per la chiave, viene restituito il valore predefinito altrimenti viene restituito il valore.

Nel nostro caso, la chiave "nepal" non è presente, quindi il programma restituisce Not Found .

Articoli interessanti...