Adding and Removing Dictionary Properties - Images: Japanese
Hey there, everyone!
Alright, let's continue on and go over some things to keep in mind when working with dictionary properties (elements), along with how to add and remove them.
First, let's take a look at which data types can be used as dictionary keys.
In other languages, the equivalent of Swift's dictionary is usually called an associative array — and in most cases, only String or Int types are allowed as keys.
In Swift, however, the rule is: "any type that conforms to the Hashable protocol can be used as a dictionary key." This means you can use things other than strings or numbers as keys.
For example, you can even use Boolean values (true and false) as keys.
let d: [Bool: String] = [true: "Hatsune Miku"] // This works just fine.
That said, there's probably no real situation where you'd need to use anything other than String or Int as a dictionary key — so sticking with String or Int is usually the safest bet. That's just the author's take, though, so use whatever fits your needs. Go with what makes sense for the situation.
Now let's try adding properties (elements) to a dictionary we've already defined. Take a look at the sample below.
var d = ["staff0": "Hatsune Miku"] d["staff1"] = "IA" print(d) // Outputs: ["staff0": "Hatsune Miku", "staff1": "IA"]
Notice the line d["staff1"] = "IA". To add a new property (element) to a dictionary, you write it in the form dictionaryName[key] = value — just like that.
And to delete a property (element) from a dictionary, you do this.
var d = ["staff0": "Hatsune Miku"] d["staff1"] = "IA" print(d) // Outputs: ["staff0": "Hatsune Miku", "staff1": "IA"] d["staff1"] = nil // Passing 'nil' removes the element. print(d) // Outputs: ["staff0": "Hatsune Miku"]
Notice the line d["staff1"] = nil. By assigning nil — in other words, writing dictionaryName[key] = nil — you can delete that property (element). Keep this pattern in mind.
Also, a dictionary declared with let becomes immutable, so if you need to modify a dictionary after creation, make sure to declare it with var. It's an easy mistake to make, so watch out.
* nil is explained in the next article.
Just like arrays, you can get the number of properties a dictionary holds by writing dictionaryName.count.
let d = [
0: "Hatsune Miku",
1: "IA"
]
print(d.count) // Outputs the number 2.
.count comes up a lot, so it's worth remembering.
You might be wondering: "What's the difference between a dictionary with Int keys and a regular array?" Great question — let's put them side by side and compare.
First, let's define each one.
let d: [Int: String] = [0: "Hatsune Miku"] // A dictionary with Int keys. let a: [String] = ["Hatsune Miku"] // A regular array.
If you print the first element from dictionary d and array a, you get this.
var d: [Int: String] = [0: "Hatsune Miku"]
var a: [String] = ["Hatsune Miku"]
print(d[0]) // Outputs: Optional("Hatsune Miku")
print(a[0]) // Outputs: Hatsune Miku
* The reason Optional("Hatsune Miku") appears is explained in the next article.
They look pretty similar at first glance.
But there's a significant difference between a dictionary with Int keys and a regular array. A regular array manages its elements with sequential numbers, while a dictionary with Int keys can use non-sequential numbers.
Let's try it out. We'll add a new value to the array — notice we're using += here.
var d: [Int: String] = [0: "Hatsune Miku"]
var a: [String] = ["Hatsune Miku"]
print(d[0]) // Outputs: Optional("Hatsune Miku")
print(a[0]) // Outputs: Hatsune Miku
a += ["IA"]
print(a[1]) // Outputs: IA
In Swift, you can't add a new element to an array by specifying an index like a[1] = "IA". Writing something like the following will cause an error.
var d: [Int: String] = [0: "Hatsune Miku"]
var a: [String] = ["Hatsune Miku"]
print(d[0]) // Outputs: Optional("Hatsune Miku")
print(a[0]) // Outputs: Hatsune Miku
a[0] = "Lily" // This is fine — it's overwriting an existing element.
a[1] = "IA" // This is an error — you can't create a new element this way.
The same applies to .insert(). Trying to insert at an index beyond the current count will cause an error.
var d: [Int: String] = [0: "Hatsune Miku"]
var a: [String] = ["Hatsune Miku"]
print(d[0]) // Outputs: Hatsune Miku
print(a[0]) // Outputs: Hatsune Miku
a.insert("IA", at: 2) // Error. You can't insert at an index beyond the current maximum.
So when adding new elements to an array, you use +=.
This means that when you add a new element to a regular array, it's always managed in sequential order starting from one more than the current maximum index.
A dictionary with Int keys, on the other hand, lets you skip numbers when storing data. Like this.
var d: [Int: String] = [0: "Hatsune Miku"]
var a: [String] = ["Hatsune Miku"]
print(d[0]) // Outputs: Optional("Hatsune Miku")
print(a[0]) // Outputs: Hatsune Miku
a += ["IA"]
print(a[1]) // Outputs: IA
d[2] = "IA" // You can store at non-sequential indices like this.
print(d[2]) // Outputs: Optional("IA")
It can get a little confusing at first, but that's the key difference between a regular array and a dictionary with Int keys. Use whichever one fits your purpose.
And since you're specifying data types at the time of declaration, you may have already guessed — just like arrays, dictionaries can only hold keys and values of the same types they were declared with.
var d: [String: String] = ["staff" : "Hatsune Miku"] d["staff1"] = true // Error. Dictionary 'd' is defined as [String: String], so you can't assign true to it.
Many modern programming languages let you get away with not thinking too hard about data types, but Swift is very strict about them. It's an easy thing to trip up on, so keep it in mind.
So that covers the things to watch out for with dictionaries, plus how to add and remove properties. It's a bit to take in, but hopefully it's making sense!
Now, if you've been running the samples in your own environment, there's probably something that's been bugging you. Take a look at this sample.
let d = ["staff": "Hatsune Miku"]
print(d["staff"]) // You might expect "Hatsune Miku", but it actually outputs Optional("Hatsune Miku").
Something's showing up as Optional("Hatsune Miku")! In the next article, we'll dig into what Optional is all about. See you there!
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.