Dictionnaire rapide (avec exemples)

Dans ce didacticiel, vous découvrirez ce qu'est un dictionnaire, la création d'un dictionnaire et certaines opérations courantes dans le dictionnaire.

Dans l'article précédent de Swift Arrays, nous avons appris comment stocker plusieurs valeurs dans une variable / constante. Dans cet article, nous allons discuter de la façon dont nous pouvons stocker des données / valeurs sous forme de paires clé / valeur.

Qu'est-ce qu'un dictionnaire?

Un dictionnaire est simplement un conteneur qui peut contenir plusieurs données sous forme de paire clé-valeur de manière non ordonnée.

Chaque valeur est associée à une clé unique et stocke les données dans une liste non ordonnée à partir de Ensembles, c'est-à-dire que vous n'obtenez pas les éléments dans le même ordre que vous avez défini les éléments dans le dictionnaire.

Vous pouvez utiliser un dictionnaire au lieu d'un tableau lorsque vous devez rechercher une valeur avec un identifiant dans la collection. Supposons que vous souhaitiez rechercher la capitale du pays. Dans ce cas, vous allez créer un dictionnaire avec le pays clé et la valeur capitale. Maintenant, vous obtenez la capitale de la collection en recherchant avec le pays clé.

En termes simples, vous associez une clé à une valeur. Dans l'exemple ci-dessus, nous avons associé un pays à sa capitale.

Comment déclarer un dictionnaire en Swift?

Vous pouvez créer un dictionnaire vide en spécifiant le key:valuetype de données entre crochets ().

Exemple 1: déclarer un dictionnaire vide

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

Lorsque vous exécutez le programme, la sortie sera:

 (:)

OU

Vous pouvez également définir un dictionnaire vide comme ci-dessous:

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

Dans le programme ci-dessus, nous avons déclaré une constante emptyDic de type dictionnaire avec une clé de type Intet une valeur de type Stringet l' avons initialisée avec 0 valeurs.

OU

Puisque Swift est un langage d'inférence de type, vous pouvez également créer un dictionnaire directement sans spécifier le type de données, mais vous devez initialiser avec certaines valeurs pour que le compilateur puisse déduire son type comme:

Exemple 2: déclarer un dictionnaire avec certaines valeurs

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

Lorsque vous exécutez le programme, la sortie sera:

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

Dans le programme ci-dessus, nous avons déclaré un dictionnaire sans définir explicitement le type mais en initialisant avec certains éléments par défaut.

L'élément est dans la paire clé: valeur où la clé est de type Stringet la valeur est de Inttype. Le dictionnaire étant une liste non ordonnée, print(someDic)les valeurs sont affichées dans un ordre différent de celui défini.

Exemple 3: création d'un dictionnaire à partir de deux tableaux

Nous pouvons également créer un dictionnaire à l'aide de tableaux.

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

Lorsque vous exécutez le programme, la sortie sera:

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

Dans le programme ci-dessus, zip(customKeys,customValues)crée une nouvelle séquence de tuple avec chaque élément représentant la valeur de customKeys et customValues. Pour en savoir plus sur le fonctionnement de zip, visitez Swit zip.

Maintenant, nous pouvons transmettre cette séquence à l' Dictionary(uniqueKeysWithValues:)initialiseur et créer un nouveau dictionnaire. Par conséquent, print(newDictionary)génère un nouveau dictionnaire avec des éléments de deux tableaux.

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

Dans le programme ci-dessus, nous avons spécifié une valeur introuvable dans le paramètre par défaut lors de l'accès au dictionnaire. Si la valeur n'existe pas pour la clé, la valeur par défaut est renvoyée, sinon la valeur est renvoyée.

Dans notre cas, la clé "nepal" n'est pas présente, donc le programme renvoie Not Found .

Articles intéressants...