Swift Dictionary
Dictionary is collection of unordered element. Each and every element of dictionary are contains key and value pair. Element value are used by specified key. role of key is an identifies of elements values.
We can define empty string in swift programming in following way.
//Create an empty dictionary
//First way
//here key and value is string types
var myDictionary : [String:String] = [:]
//Second way
//key and value are a Integer type
var myIntDictionary:Dictionary<Int,Int> = [:]
//Third way
//key is Integer type and value are String type
var month=[Int:String]()
print(myDictionary)
print(myIntDictionary)
print(month)
Output
[:]
[:]
[:]
In above example given three different way to create an empty dictionary. Here given proper way to define dictionary element like that is the type of key and what type value it will stored. Let see an example how to set initial values to dictionary element, which is working on specified data and key value type.
//Set initial values of dictionary elements
var numberRecords : [String:Int] = ["one":1,"two":2,"three":3]
var errorStatus : Dictionary<String,Int> = ["logical":0,"compilation":2,"exeption":0]
var monthRecords = [Int:String]() //Empty dictionay
monthRecords = [1:"Jun",2:"Fab",3:"Mar"]
//Display dictionary element
print(numberRecords)
print(errorStatus)
print(monthRecords)
Output
["three": 3, "two": 2, "one": 1]
["exeption": 0, "compilation": 2, "logical": 0]
[2: "Fab", 3: "Mar", 1: "Jun"]
In this example provide initial value to dictionary element. observe that here the result is an in unordered sequence. So dictionary element is not depending upon providing the inserting sequence.
Swift compiler are smart when we provide initial value to dictionary, Then there are not compulsory to mentioning their key and value type.
var coinCollection=[
"oneRupee":9,
"twoRupee":4,
"tenRupee":13
]
print(coinCollection)
Output
["oneRupee": 9, "twoRupee": 4, "tenRupee": 13]
In this example compiler are provide dictionary data type, by using of this initialize values. Here key is form of string value and key data is form of an integers. So In case when we assign initial values to dictionary element then that are not compulsory to define elements type.
Basic operations of dictionary
Count dictionary Element:
var myDictionary=["roundOne":23,
"roundTwo":40,
"roundThree":21]
print("Total Element in dictionary : \(myDictionary.count)")
Output
Total Element in dictionary : 3
Add new Element
var myDictionary=["r1":23,
"r2":40,
"r3":21]
print("Before Add new element : \(myDictionary)")
//add new element
myDictionary["r4"]=23
print("After Add new element : \(myDictionary)")
Output
Before Add new element : ["r3": 21, "r1": 23, "r2": 40]
After Add new element : ["r4": 23, "r1": 23, "r2": 40, "r3": 21]
Update Element
var myDictionary=["r1":23,
"r2":40,
"r3":21]
print("Before Update element : \(myDictionary)")
//add new element
myDictionary["r3"]=300
myDictionary["r2"]=200
myDictionary["r1"]=100
print("After Update element : \(myDictionary)")
Output
Before Update element : ["r1": 23, "r2": 40, "r3": 21]
After Update element : ["r1": 100, "r2": 200, "r3": 300]
This is basic example to update dictionary key value. updateValue(_:forKey:) method are used to modified specified key element value.
var myDictionary=["r1":23,
"r2":40,
"r3":21]
print("Before Update element : \(myDictionary)")
//add new element
myDictionary.updateValue(300,forKey:"r3")
myDictionary.updateValue(200,forKey:"r2")
myDictionary.updateValue(100,forKey:"r1")
print("After Update element : \(myDictionary)")
Output
Before Update element : ["r3": 21, "r2": 40, "r1": 23]
After Update element : ["r3": 300, "r2": 200, "r1": 100]
Check empty dictionary
var myDictionary=[Int:Int]()
if myDictionary.isEmpty {
print("Initial Dictionary is empty")
}else{
print("Initial Dictionary is not empty")
}
myDictionary[0]=1
if myDictionary.isEmpty {
print("After Dictionary is empty")
}else{
print("After Dictionary is not empty")
}
Output
Initial Dictionary is empty
After Dictionary is not empty
Remove Dictionary
There are two way to remove existing dictionary element. First method is set dictionary element is to nil. nil are used to represent Nothing and dictionary are delete this element. And other method removeValue(forKey:) function are used.
var myDictionary=["r1":23,
"r2":40,
"r3":21]
print("Dictionary element : \(myDictionary)")
print("First method are remove element")
myDictionary["r1"]=nil //remove r1 key element
print("After Remove element : \(myDictionary)")
if let removeData=myDictionary.removeValue(forKey:"r2"){
print("Second method are remove element : \(removeData)")
}
print("After Remove element : \(myDictionary)")
Output
Dictionary element : ["r1": 23, "r2": 40, "r3": 21]
First method are remove element
After Remove element : ["r2": 40, "r3": 21]
Second method are remove element : 40
After Remove element : ["r3": 21]
Sort Dictionary Elements
let dictionary=[6:"Six",4:"Four",9:"Nine",10:"Ten",1:"One"]
//Get sorted key in array form
let assendingKey=Array(dictionary.keys).sorted(by:<)
let desendingKey=Array(dictionary.keys).sorted(by:>)
//Get sorted key and value pair in tuple form
let assendingKeyValue=dictionary.sorted(by:<)
let desendingKeyValue=dictionary.sorted(by:<)
print("\(dictionary)")
print("\(assendingKey)")
print("\(desendingKey)")
print("\(assendingKeyValue)")
print("\(desendingKeyValue)")
Output
[6: "Six", 10: "Ten", 4: "Four", 9: "Nine", 1: "One"]
[1, 4, 6, 9, 10]
[10, 9, 6, 4, 1]
[(key: 1, value: "One"), (key: 4, value: "Four"), (key: 6, value: "Six"), (key: 9, value: "Nine"), (key: 10, value: "Ten")]
[(key: 1, value: "One"), (key: 4, value: "Four"), (key: 6, value: "Six"), (key: 9, value: "Nine"), (key: 10, value: "Ten")]
Note that we can get array tuple element in this ways
let dictionary=[6:"Six",4:"Four",9:"Nine",10:"Ten",1:"One"]
//Get sorted key and value pair in tuple form
let assendingKeyValue=dictionary.sorted(by:<)
//Display element
print("\(assendingKeyValue[0].value)")
print("\(assendingKeyValue[3].key) : \(assendingKeyValue[3].value)")
Output
One
9 : Nine
Merge two dictionary element: merge function are add new dictionary element by new keys. When key is are ready exist in this case this are skip this element.
var dictionary = ["income": 100000, "saving": 20000]
//merge two dictionary element
dictionary.merge(["tax": 200, "income": 50000]) { (item, _) in item }
print(dictionary)
Output
["saving": 20000, "tax": 200, "income": 100000]
Suppose assume that we are need to merge element in update form. Then we can do this way.
var dictOne = [1: "One",4:"Four"]
var dictTwo = [2: "Two",5:"Five",1:"Ten"]
print("Before merge")
print("dictOne : \(dictOne) ")
print("dictTwo : \(dictTwo) ")
//combine two dictionary element in update form
extension Dictionary {
mutating func merge(dict: [Key: Value]){
for (key, value) in dict {
updateValue(value, forKey: key)
}
}
}
print("After merge")
dictOne.merge(dict:dictTwo)
print("dictOne : \(dictOne) ")
print("dictTwo : \(dictTwo) ")
Output
Before merge
dictOne : [4: "Four", 1: "One"]
dictTwo : [2: "Two", 5: "Five", 1: "Ten"]
After merge
dictOne : [5: "Five", 2: "Two", 4: "Four", 1: "Ten"]
dictTwo : [2: "Two", 5: "Five", 1: "Ten"]
Note that in this example we are merging of two dictionary. If new element key are already exist then modify the key element by new value.
Iterating the dictionary element
We can iterate dictionary element by using for-loops and while-loop.
let dictionary=[6:"Six",4:"Four",9:"Nine",10:"Ten",1:"One"]
print("Using for loop")
//Using for loop
for (key,value) in dictionary {
print("\(key) : \(value)")
}
var index=0
let keyStore = Array(dictionary.keys)
print("Using while loop")
while(index<dictionary.count){
print("\(keyStore[index]) : \(dictionary[keyStore[index]]!)")
index+=1
}
Output
Using for loop
6 : Six
10 : Ten
4 : Four
9 : Nine
1 : One
Using while loop
6 : Six
10 : Ten
4 : Four
9 : Nine
1 : One
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment