Swift program to get the index for a key in Dictionary

Swift program to get the index for a key in Dictionary :

In this tutorial, we will learn how to get the index of a key in swift Dictionary. Many time we need the index for a key in a dictionary. We can use this process at that time. Let me show you with an example :

Method to use : index(forkey:) :

index(forkey:) is an instance method. We need to pass the key to this method and it will return the index for that key.If the key is not available , it will return nil. For example :

let weeksDictionary = ["sun" : 0,"mon" : 1,"tue" : 2,"wed" : 3,"thu" : 4,"fri" : 5,"sat" : 6]
let index = weeksDictionary.index(forKey: "fri")

print(weeksDictionary[index!].value)

It will print 5. But what about the below program :

let weeksDictionary = ["sun" : 0,"mon" : 1,"tue" : 2,"wed" : 3,"thu" : 4,"fri" : 5,"sat" : 6]
let index = weeksDictionary.index(forKey: "fff")

print(weeksDictionary[index!].value)

It will throw one exception because the value of index is nil. So, we should check for nil value always or safely unwrap it like below :

let weeksDictionary = ["sun" : 0,"mon" : 1,"tue" : 2,"wed" : 3,"thu" : 4,"fri" : 5,"sat" : 6]
if let index = weeksDictionary.index(forKey: "fri"){
    print(weeksDictionary[index].value)
}else{
    print("No values found..")
}