English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn what a dictionary is, how to create a dictionary, and some common operations in a dictionary.
In the previousSwift ArrayIn the article, we learned how to declare variables/Store multiple values in constants. In this article, we will discuss how to store data/Values are stored as key-value pairs.
A dictionary is just a container that can store multiple data as key-value pairs in an unordered manner.
Each value is associated with a unique key and stores data in an unordered list asCollectionThat is to say, the order in which you obtain the elements is different from the order in which you define the items in the dictionary.
When you need to find a value with a specific identifier in a collection, you can use a dictionary instead of an array. Suppose you want to search for the capital of this country. In this case, you will create a dictionary with the country and capital city as key-value pairs. Now, you can obtain the value: capital by searching for the key: country from the collection.
In simple terms, you pair keys with values. In the above example, we pair a country with its capital.
You can create an empty dictionary by specifying key: value data type within square brackets[].
let emptyDic:[Int:String] = [:] print(emptyDic)
When running the program, the output is:
[:]Or
You can also define an empty dictionary as follows:
let emptyDic:Dictionary<Int, String> = [:] print(emptyDic)
In the above program, we declared a constant emptyDic of type dictionary with Int-type keys and String-type values, and initialized it with a 0 value.
Or
Since Swift is a type inference language, you can also create a dictionary without specifying the data type, but you must initialize it with some values so that the compiler can infer it as:
let someDic = ["a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9] print(someDic)
When running the program, the output is:
["b": 2, "a": 1, "i": 9, "c": 3, "e": 5, "f": 6, "g": 7, "d": 4, "h": 8]
In the above program, we declared a dictionary but did not explicitly define the type, instead initializing it with some default elements.
Elements are located in key:value pairs, where the key type is String and the value type is Int. Since dictionaries are unordered lists, print(someDic) outputs values in an order different from the defined order.
We can also use an array to create a dictionary.
let customKeys = ["Facebook", "Google", "Amazon"] let customValues = ["Mark", "Larry", "Jeff"] let newDictionary = Dictionary(uniqueKeysWithValues: zip(customKeys,customValues)) print(newDictionary)
When running the program, the output is:
["Amazon": "Jeff", "Google": "Larry", "Facebook": "Mark"]
In the above program, zip(customKeys,customValues) creates a new tuple sequence, each element representing values from customKeys and customValues.
Now, we can pass this sequence to the Dictionary(initialValue: Dictionary(uniqueKeysWithValues:)) initializer and create a new Dictionary. Therefore, print(NewDictionary) outputs a new Dictionary containing elements from both arrays.
As an array, you can use index syntax to access dictionary elements. You need to include the key of the value you want to access in the brackets after the dictionary name.
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 running the program, the output is:
Optional(1) Optional(8)
You can also use for-in loop to access dictionary elements.
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 running the program, the output is:
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
You can add elements to the dictionary using index syntax. You need to include New key As an index and assign a new value to the Dictionary type.
var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"] someDictionary["Japan"] = "Tokyo" print(someDictionary)
When running the program, the output is:
["Japan": "Tokyo", "China": "Beijing", "India": "NewDelhi", "Nepal": "Kathmandu"]
In the above example, we used index syntax to create a new key-value pair "Japan": "Tokyo" in the given dictionary.
You can also use index syntax to change the value associated with a specific key:
var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"] someDictionary["Nepal"] = "KATHMANDU" print(someDictionary)
When running the program, the output is:
["China": "Beijing", "India": "NewDelhi", "Nepal": "KATHMANDU"]
This property determines whether the dictionary is empty. If the dictionary does not contain any values, it returns true, otherwise it returns false.
let someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"] print(someDictionary.isEmpty)
When running the program, the output is:
false
This property is used to access the first element of the dictionary.
let someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"] print(someDictionary.first)
When running the program, the output is:
Optional((key: "China", value: "Beijing"))
This property returns the total number of elements (key-value pairs) in the dictionary.
let someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"] print(someDictionary.count)
When running the program, the output is:
3
This property returns all the keys in the dictionary.
var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"] let dictKeys = Array(someDictionary.keys) print(dictKeys)
When running the program, the output is:
["China", "India", "Nepal"]
Similarly, you can use values property to get all the values in the dictionary.
This function is used to delete and return the value specified by the key from the dictionary. Both of these key-value pairs will be removed from the dictionary.
var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"] let val = someDictionary.removeValue(forKey: "Nepal") print(val) print(someDictionary)
When running the program, the output is:
Optional("Kathmandu") ["India": "NewDelhi", "China": "Beijing"]
Similarly, you can also use removeAll The function clears the dictionary.
1.When accessing elements in a dictionary using the subscript syntax in Swift, you must ensure that the key is located in the index, otherwise you will getnilValue. Let's see an example:
var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"] let val = someDictionary["Japan"] print(val)
When running the program, the output is:
nil
In the above program, there is no key Japan . Therefore, when you try to access the key "Japan when you access it, you will get a nil value.
2.Similarly, keys are case-sensitive in Swift, so you must ensure that you use the correct case for the key/Value. Otherwise, you will get a nil value. Let's see an example:
var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"] let val = someDictionary["nepal"] print(val)
When running the program, the output is:
nil
In the above program, there is no key 'nepal'. Therefore, when you try to access the key 'nepal', you will get a nil value.
3.If the value of the given key does not exist, there is also another way to provide a default value. Let's see an example in the following demonstration:
var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"] let val = someDictionary["nepal", default:"Not Found"] print(val)
When running the program, the output is:
Not Found
In the above program, we specified a default value in the default parameter when accessing the dictionary. If the value of the key does not exist, the default value is returned, otherwise the value is returned
In our example, the key"nepal"Not found, therefore the program returns the default value: Not Found.