Dictionaries in Swift are like containers that hold pairs of information: a key and its corresponding value. Think of them as organized lists where each item has a unique label (key) associated with some data (value).
In this tutorial, you will learn how to create a new, empty dictionary in Swift.
There are a few ways to create an empty dictionary in Swift. Below I demonstrate how to do it.
Method 1: The Speedy Shortcut
In the below code snippet you will create an empty Dictionary that has a key and a value of a String data type. First, you name the dictionary, then define the types for keys and values within square brackets, and finally, create an empty Swift dictionary using parentheses.
let myDictionary = [String:String]()
When you write let myDictionary = [String: String]()
in Swift, you are making an empty dictionary that holds both keys and values of the String type. It’s like an empty box where you can put words (keys) and their definitions (values), but each word and its definition must be made up of text (String) in this box. Once you’ve created this dictionary as a constant let
, You can’t change the box itself, like its emptiness or the types it can contain.
Method 2: Type Annotation and Literal
You can make an empty dictionary differently by changing how you initialize it. But remember, ‘Explicit Explorer‘ isn’t the official name according to Swift’s documentation, it’s a descriptive term I used to explain this method clearly.”
let myDictionary2:[String:String] = [:] let myDictionary3:[String:Int] = [:]
As before, you’re specifying the types ([String: String] or [String: Int])
that the dictionary will contain.
myDictionary2
andmyDictionary3
declare dictionaries with specific types for keys and values.myDictionary2
holds strings for both keys and values, just like the first method.myDictionary3
has keys as strings, but the values are integers.
With [:]
, You’re basically telling the same things to Swift, “You want an empty dictionary that’s ready to store my specific type of data, but it’s empty for now”.
Conclusion:
So, there you have it! You’ve made an empty dictionary, which is like an empty canvas waiting for you to add key-value pairs later in my program. Just like an empty drawer waiting for me to fill it with treasures, an empty dictionary doesn’t hold anything right now, but it’s ready for you to store valuable information as your program progresses.
You’re ready to level up and learn about adding items to dictionaries. I will be happy to guide you through it as well!
Ready for more Swift code examples and tutorials? Check out the Swift Code Examples page.