How To Use Dictionary In iOS Swift

Swift dictionary is used to store key value pair data. The stored key and value data type should be consistent. The key value data type can be declared at the dictionary variable declaration time, or the data type can be identified by the data assigned to the dictionary variable at run time. This article will give you some examples about how to use swift dictionary variable.

1. Define Swift Dictionary Object.

There are several ways to define a dictionary object variable in swift. But you should follow below rules for every way.

  1. Declare the dictionary key value data type explicitly at declaration time. Otherwise the data type will be determined when you assign data to the dictionary variable. If you want to hold any data type in the dictionary, you can declare the key or value with Any data type class. There is an example in below source code.
  2. Initialize the dictionary object before use it.
  3. The dictionary key should be Hashable.
// Declare a dictionary object and assign initial value. The key & value data type are all String type.
var dictUser:Dictionary<String,String> = ["name":"jerry", "salary":"10000"]

print(dictUser)

// The key & value data type will be decided by the assigned data value.
var dictDept = ["deptName":"Dev", "deptDesc":"Develop iOS app"]

print(dictDept)

// You can use Any data type class for key or value. Below example will hold any data type data in dictionary value.
var dictEmp = Dictionary<String, Any>()

dictEmp = ["empName":"Tom", "empSalary":10000]

print(dictEmp)

// declare an empty dictionary object variable.
var dictWork = [String : String]()

// assign value to above dictionary variable.
dictWork = ["task1":"coding", "task2":"debug"]

print(dictWork)

Run above source code will get below result.

["name": "jerry", "salary": "10000"]
["deptName": "Dev", "deptDesc": "Develop iOS app"]
["empName": "Tom", "empSalary": 10000]
["task1": "coding", "task2": "debug"]

2. Get Dictionary Value By Key.

var dictUser:Dictionary<String,String> = ["name":"jerry", "salary":"10000"]

// Get value by "name" key.
var name = dictUser["name"]

print(name)

// The value is optional variable, so force unwrap it's value.
print(name!)

// If the key do not exist then return nil.
var email = dictUser["email"]

print(email)

Below is the code execution result.

Optional("jerry")

jerry

nil

3. Get Swift Dictionary Item Count.

Use count property to get the item counts in a swift dictionary.

var dictUser:Dictionary<String,String> = ["name":"jerry", "salary":"10000"]

var count = dictUser.count

print("dictUser has \(count) elements.")

Below is the code execution result.

dictUser has 2 elements.

4. Add Element To Swift Dictionary.

var dictUser:Dictionary<String,String> = ["name":"jerry", "salary":"10000"]

// add a new element in dictionary object.
dictUser["email"] = "[email protected]"

print(dictUser)

Below is the code execution result.

["salary": "10000", "email": "[email protected]", "name": "jerry"]

5. Update Dictionary Element By Key Directly.

var dictUser:Dictionary<String,String> = ["name":"jerry", "salary":"10000"]

// Update salary value directly.
dictUser["salary"] = "80000"

print(dictUser)

Below is above code execution result.

["salary": "80000", "name": "jerry"]

6. Invoke Dictionary Object’s updateValue(forKey:) Method To Update Dictionary Element.

You can also call dictionary object’s updateValue(forKey:) method to change element value by key, and this method will return the original key mapped value before updated.

var dictUser:Dictionary<String,String> = ["name":"jerry", "salary":"10000"]

// Invoke updateValue method to update related key's value, this method will return the original value for that key.
let oldValue = dictUser.updateValue("89999", forKey: "salary")

print("Old value for key \"salary\" is \(oldValue)")

print(dictUser)

Below is above code execution result.

Old value for key "salary" is Optional("10000")
["salary": "89999", "name": "jerry"]

7. Remove Swift Dictionary Element.

You can use dictionary object’s removeValue(forKey:) method to remove a dictionary element by key.

// Declare a dictionary object and assign initial value. The key & value data type are all String type.
var dictUser:Dictionary<String,String> = ["name":"jerry", "salary":"10000"]

// Invoke removeValue method to remove the key value pair, this method will return the removed value for that key.
var removedValue = dictUser.removeValue(forKey: "salary")

print("Removed value for key \"salary\" is \(removedValue!)")

print(dictUser)

Run above code will get below output.

Removed value for key "salary" is 10000
["name": "jerry"]

You can also use remove(at: Index) method to remove a dictionary element by provided index.

// Declare a dictionary object and assign initial value. The key & value data type are all String type.
var dictUser:Dictionary<String,String> = ["name":"jerry", "salary":"10000"]

// Get Index for provided key, because the return index is an optional type variable ( Index? ), so use ! to force unwrap it to Index type.
var index:Dictionary<String, String>.Index = dictUser.index(forKey: "name")!

var removedElement = dictUser.remove(at: index)

print("Removed element is \(removedElement)")

print(dictUser)

Below is above code execution result.

Removed element is (key: "name", value: "jerry")

["salary": "10000"]

8. Swift Dictionary Variable Elements Iteration.

8.1 Iterate Swift Dictionary Use For Loop.

var dictUser:Dictionary<String,String> = ["name":"jerry", "salary":"10000"]

for (key, value) in dictUser{

    print("key : \(key), value : \(value)")
}

Below is above code execution result.

key : salary, value : 10000
key : name, value : jerry

8.2 Iterate Keys Of Swift Dictionary.

Use Dictionary.keys property to get all keys. Then loop in the keys to get related value.

var dictUser:Dictionary<String,String> = ["name":"jerry", "salary":"10000"]

for key in dictUser.keys{

    // Force unwrap optional value.
    var value = dictUser[key]!
    
    print("key : \(key), value : \(value)")
}

Below is above code execution result.

key : salary, value : 10000
key : name, value : jerry

8.3 Iterate Values Of Swift Dictionary.

Use Dictionary.values property to get all values.

var dictUser:Dictionary<String,String> = ["name":"jerry", "salary":"10000"]

for val in dictUser.values{
    
    print("value : \(val)")
}


var valueArr = Array(dictUser.values)

print(valueArr)

Run above code will get below result.

value : jerry
value : 10000
["jerry", "10000"]

Reference

  1. How To Fix Error ‘Value Of Optional Type Must Be Unwrapped To A Value Of Type’ In Swift. This reference article will tell you what is optional variable in swift and how to unwrap it’s value correctly.
READ :   How To Rename IBOutlet Variable Or IBAction Function Without Lose Connection In Swift

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.