This tutorial assumes that you know the concept of an Array in Swift. Dictionaries are nothing other than the advanced layer of an Array!
If you want to store information about students going to the school like their Name, Surname, ID, Grades, and Address, keeping it as an array is a good idea, but what if some information is missing. For example, a student is not graded yet, and to find out things like that makes it difficult for you to figure out.
var student: [Any] = [
"Jared",
"Davidson",
25062022,
98.4,
"Yellowknife, Mars"]
Not to worry about, as Dictionary solves this issue. Like you have seen different blocks while filling out the registration form or a signup page, each asking for your information and helping to insert a value at a perfect spot, just like that, we are giving a key to our array to catch the info quickly of a student.
For dictionaries, write down the key first, the same as writing a String item, then adding a colon and the value. It's basically has Key : Value pairs where if you need to check any information, such as Name, Address or ID of the student, you simply need to access the key name corresponding to it and dictionary tells you its value.
var student = [
"Name": "Jared",
"Surname": "Davidson",
"ID": "25062022",
"Grades": "98.4",
"Address": "Yellowknife, Mars"
]
print(student["Name"])
print(student["Address"])
print(student["ID"])
// prints
Optional("Jared")
Optional("Yellowknife, Mars")
Optional("25062022")
Here in this code snippet, you'll find that each value that you try to access is an optional wrapped value, dictionary has all its key's value optionally wrapped because at runtime there is no guarantee if there is a value for a given key or not.
That's all for the concept of Dictionaries. Congratulations! Keep pushing yourself forward, learning things. We encourage you to learn more related topics next like How to generate random number in Swift, Functions in Swift. Till then,
Eat. Sleep. Swift Anytime. Repeat
Top comments (0)