What are Dictionaries? - Images: Japanese
Hey there, everyone!
Last time we covered arrays — nice work getting through that. This time, let's dig into something called a dictionary.
A dictionary in Swift is essentially the same concept as what other languages call an associative array, a hash, or a map.
By the way, dictionary comes from the English word dictionary, and you'll often hear it referred to as a Dictionary (with a capital D) in Swift circles too.
Let's start by understanding what a dictionary actually is. Think back to indexed arrays (arrays that use sequential numbers as indices). When you define an array, it looks something like this.
let fruits = [
"リンゴ",
"オレンジ",
"グレープ"
]
And to access each element, you'd write something like fruits[0] — placing a sequential number inside [] next to the array name, right?
let fruits = [
"リンゴ",
"オレンジ",
"グレープ"
]
print(fruits[0]) // Outputs "Apple".
So a regular array is a collection of data managed by sequential numbers — but a 'dictionary' is a collection of data managed by 'custom names (identifiers)'.
Take a look at the code below. We've taken the same data from the array above and defined it as a dictionary.
let fruits = [
"apple": "リンゴ",
"orange": "オレンジ",
"grape": "グレープ"
]
To print "Apple" from the dictionary above, you'd do this.
let fruits = [
"apple": "リンゴ",
"orange": "オレンジ",
"grape": "グレープ"
]
print(fruits["apple"])
Look at what's inside the () of print(). You can see fruits["apple"] — the string apple is written inside [].
This is how you access each element — by writing an identifier inside []. Remember this pattern: dictionaryName[identifier].
With a regular array you could only manage data by sequential numbers, but with a dictionary you can manage it in a completely different way — which can make data organization much more intuitive depending on the situation.
For example, let's say you want to store employee names paired with their phone numbers. Using only regular arrays, you'd end up with something like this.
let staff = [
"初音ミク",
"IA"
]
let phoneNumber = [
"080xxxxyyyy",
"090xxxxyyyy"
]
Even if you design it so that each element in staff matches its corresponding element in phoneNumber, it's not exactly the clearest approach, is it?
Now try the same thing with a dictionary.
let staffPhoneNumber = [
"初音ミク": "080xxxxyyyy",
"IA": "090xxxxyyyy"
]
Much clearer, right? The employee names and phone numbers are paired together in an obvious, readable way. That's the basic idea behind using a dictionary.
The identifiers used to manage a 'dictionary' are called 'keys'. Keys are also sometimes referred to as 'property names'.
In the example below, apple, orange, and grape are each a key (property name).
let fruits = [
"apple": "リンゴ",
"orange": "オレンジ",
"grape": "グレープ"
]
Each piece of data stored in the dictionary is called a 'value'. And each pair of a 'key' and a 'value' together is called a 'property' or an 'element'.
For the first entry in the dictionary above, the 'key' is 'apple', the value is 'Apple', and the pair of 'apple' and 'Apple' together is the 'property' (element).
One thing to note: terms like key, property, element, property name, and value can vary depending on the language, book, or person you're learning from.
So calling a key an index or property name, or calling a value just its contents, is perfectly fine. The terminology may differ, but they all refer to the same things.
Now let's go over the syntax for declaring a dictionary and everything that goes along with it. First up: declaring without initializing.
var d: [String: Int] // Declares a dictionary.
That's all you need to declare a dictionary. The following notation also works.
var d: Dictionary<String, Int> // Declares a dictionary.
When declaring a dictionary, you write it as 'dictionaryName: [DataType: DataType]', or 'dictionaryName: Dictionary<DataType, DataType>'.
The dictionaryName: Dictionary<DataType, DataType> form is a bit verbose, so most people tend to use dictionaryName: [DataType: DataType] instead.
It can be a bit easy to mix things up, so let's compare it side by side with an array declaration.
var d: [String: Int] // Declares a dictionary. var a: [Int] // Declares an array. var _d: Dictionary<String, Int> // Declares a dictionary. var _a: Array<Int> // Declares an array.
Comparing with array declarations, you can see that a dictionary specifies two data types. But overall, the declaration style is pretty similar.
Just like with arrays, trying to access a dictionary that has only been declared — without being initialized — will cause an error.
var d: [String: Int] // Declares a dictionary. var a: [Int] // Declares an array. print(d) // Error. print(a) // Error.
So when creating a dictionary, it's common practice to initialize it at the same time. Same deal as with arrays.
There are a few ways to initialize a dictionary. One approach is to assign [:] to it, like this.
This is similar to how arrays work, so let's look at them together.
var d: [String: Int] = [:] // Declares and initializes a dictionary. var a: [Int] = [] // Declares and initializes an array. print(d) // Outputs "[:]". print(a) // Outputs "[]".
Arrays are initialized by assigning '[]', while dictionaries are initialized by assigning '[:]'.
Another option is to use an initializer.
var d = [String: Int]() // Declares and initializes a dictionary. var a = [Int]() // Declares and initializes an array. var _d = Dictionary<String, Int>() // Declares and initializes a dictionary. var _a = Array<Int>() // Declares and initializes an array. print(d) // Outputs "[:]". print(a) // Outputs "[]".
※ Initializers are covered in a later article.
Here you're assigning [String: Int]() or Dictionary<String, Int>(). Just like with arrays, this is still an assignment, so make sure not to mix up = and :.
var d: [String: Int]() // Error. You need '=' not ':'. var _d: Dictionary<String, Int>() // Error. You need '=' not ':'.
You can also initialize a dictionary by writing out the values directly using [] and :. It looks like this.
As a bit of practice, note that we're using [String: String] instead of [String: Int] for the data types here — pay attention to that too.
var d: [String: String] = [ // Declares and initializes a dictionary.
"apple": "リンゴ",
"orange": "オレンジ"
]
The key goes on the left side of :, and the value goes on the right. Each property (element) is separated by ,. By the way, a trailing , after the last entry is optional.
var d: [String: String] = [
"apple": "リンゴ",
"orange": "オレンジ", // In some languages this would be invalid, but in Swift a trailing comma is fine.
]
Just like with variables and arrays, if the type of the data being assigned is clear, you can omit the explicit type annotation.
var d = [ // You can omit ': [String: String]' like this.
"apple": "リンゴ",
"orange": "オレンジ",
]
However, if you use '[:]' as shown below, the type can't be inferred internally, so you cannot omit the type annotation.
var d = [:] // Error — the type cannot be inferred.
And just like variables and constants, declaring with var makes it mutable, while let makes it immutable.
var d = [ // This dictionary can be modified.
"apple": "リンゴ",
"orange": "オレンジ",
]
let _d = [ // This dictionary cannot be modified.
"apple": "リンゴ",
"orange": "オレンジ",
]
Keep that in mind too.
That covers the overview and declaration basics of dictionaries. There are quite a few rules to keep track of — hopefully it's not too overwhelming!
In the next article, we'll look at how to add and remove elements from a dictionary.
That's all for now — see you in the next one!
This article was written by Sakurama.
Author's beloved small mammal |
桜舞 春人 Sakurama HarutoA Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him. |
If you find any errors or copyright issues, please contact us.