Working with Dictionary in Swift. Code Examples.

This page contains different code snippets on how to work with Dictionary in Swift.

Create Empty Dictionary

// Create an empty dictionary
let myDictionary = [String:String]()

// Another way to create an empty dictionary
let myDictionary2:[String:String] = [:]

// Keys in dictionary can also be of type Int
let myDictionary3 = [Int:String]()

 

Add Item To a Dictionary

// Create a Dictionary with two elements
var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"]

// print to preview
print(myDictionary)

// Add a new key with a value
myDictionary["user_id"] = "f5h7ru0tJurY8f7g5s6fd"

// We should now have 3 key value pairs printed
print(myDictionary)

 

Loop Through Dictionary

// Create a Dictionary with two elements
var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"]

// Loop through dictionary keys and print values
for (key,value) in myDictionary {
    print("\(key) = \(value)")
}

 

Remove Item

// Create a Dictionary with two elements
var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"]

// print to preview
print(myDictionary)

// Remove item for a key
myDictionary.removeValue(forKey: "first_name")

// print dictionary to preview
print(myDictionary)

Remove All Items

// Create a Dictionary with two elements
var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"]

// Remove all elements from a Dictionary
myDictionary.removeAll()

// Print dictionary to preview
print(myDictionary)

 


Leave a Reply

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

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!