What is iOS swift type in a Dictionary?

Share

In Swift language, the Object type Dictionary stores affiliations between keys, which must all be the same sort and value in a collection. It does this without ordering. Swift does strict checking to prevent entering a wrong type in a Dictionary, even by mistake.

Each value has its own unique key, which is an identifier for that value used for storing a value which can be referenced and looked up later using the same key. Dictionary is used when there is a need to look up values based on their identifier, just like a real-world Dictionary is used to look up the definition for a particular word. A Dictionary key can either be an integer or a string without a restriction, but has to be unique throughout the Dictionary.

If a Dictionary is assigned to a variable, it is always mutable, meaning it can be altered by adding, removing, or changing items. But in a case doled out to a constant, at that point that Dictionary is immutable, and its size and contents cannot be altered.

Creating a Dictionary

We can create an empty Dictionary of a type using initializer syntax:

var someDict = [KeyType: ValueType]()
//example
var namesOfIntegers = [Int: String]()

We could also declare like this:

var someDict: [KeyType: ValueType] = [:]
//for example
var namesOfIntegers: [Int: String] = [:]

This will create an empty Dictionary of type [Int: String]. The other example already provides type information. Therefore, an empty Dictionary can be created with an empty Dictionary literal, written as [:] (a colon inside a pair of square brackets). These key-value pairs can be written as a list, separated by commas and surrounded by a pair of square brackets:

[key 1: value 1, key 2: value 2, key 3: value 3]

The example below creates a Dictionary to store the names of countries around the world. In this Dictionary, the keys are the countries, and the values are the capitals of these countries:

var countries: [String: String] = ["Nigeria": "Abuja", "Turkey": "Istanbul"]

The countries Dictionary is declared as having a type of [String: String], which means “a Dictionary whose keys are of type String, and whose values are also of type String”.

We don’t have to type in the type of the Dictionary, on the off chance that it’s been initialized with a Dictionary literal whose keys and values have consistent types. The initialization of countries could have been written in a shorter form instead:

var countries = ["Nigeria": "Abuja", "Turkey": "Istanbul"]

Since all keys and values within the literal are of the same type as each other, Swift can gather that [String: String] is the proper type to utilize for the countries Dictionary.

Accessing and modifying a Dictionary

A Dictionary is accessed and modified through its methods and properties, or by using subscript syntax. To access Istanbul, for example, we do this:

var countries = ["Nigeria": "Abuja", "Turkey": "Istanbul"]
var capitalOfTurkey = countries["Turkey"]
print("\(capitalOfTurkey!)")
// prints "Istanbul"

Note that the exclamation mark or banging behind capitalOfTurkey in the print statement is to force unwrap the result, as it will print “Optional(“Istanbul”)” without it.

We can discover the number of items in a Dictionary by checking its count property:

var countries = ["Nigeria": "Abuja", "Turkey": "Istanbul"]
print("Only \(countries.count) countries are in the dictionary.")
// Only 2 countries are in the dictionary.

Speaking of modification, a new item can be added to a Dictionary using subscript syntax. Then we declare a new key of the appropriate type as the subscript index, and assign a new value to it of the appropriate type:

. countries["Ghana"] = "Accra"
. // the countries dictionary now contains 3 items

We can also use subscript syntax to remove a key-value pair from a Dictionary by assigning a value of nil to that key. For example:

var countries = ["Nigeria": "Abuja", "Turkey": "Istanbul"]
countries["Ghana"] = "Accra"
countries["Ghana"] = nil
print( "Capital of Nigeria is \(countries["Nigeria"] ?? " ")" )
// Capital of Nigeria is Optional("Lagos")
print( "Capital of Turkey is \(countries["Turkey"] ?? " ")")
// Capital of Turkey is Optional("Istanbul")
print( "Capital of Ghana is \(countries["Ghana"])" )
// Capital of Ghana is nil

If we try printing countries, we will realize Ghana and its capital have been removed. Let’s try!

var countries = ["Nigeria": "Abuja", "Turkey": "Istanbul"]
countries["Ghana"] = "Accra"
countries["Ghana"] = nil
print(countries)
// prints["Nigeria": "Abuja", "Turkey": "Istanbul"]

The value associated with a particular key can also be changed using subscript syntax:

countries["Turkey"] = "Ankara"
// the value for "Turkey" has been changed to "Ankara"

With this, if we try printing countries again, we will see the updated value of the capital of Turkey. Let’s try:

var countries = ["Nigeria": "Abuja", "Turkey": "Istanbul"]
countries["Ghana"] = "Accra"
countries["Turkey"] = "Ankara"
print(countries)

Iterating over a Dictionary

A for-in-loop can be used to iterate over the whole set of key-value pairs in a Dictionary. Each item in the Dictionary is returned as a (key, value) tuple. As part of the iteration, we can decompose the tuple’s members into temporary constants or variables:

var countries = ["Nigeria": "Abuja", "Turkey": "Istanbul"]
countries["Ghana"] = "Accra"
countries["Turkey"] = "Ankara"
for (country, capital) in countries {
print("\(country): \(capital)")
}
// Nigeria: Abuja
// Turkey: Ankara
// Ghana: Accra

We can also retrieve an iterable collection of a Dictionary’s keys or values by accessing its keys and values properties:

var countries = ["Nigeria": "Abuja", "Turkey": "Istanbul"]
countries["Ghana"] = "Accra"
countries["Turkey"] = "Ankara"
for country in countries.keys {
print("Country name is: \(country)")
}
// Country name is: Nigeria
// Country name is: Turkey
// Country name is: Ghana
for capital in countries.values {
print("Capital name is: \(capital)")
}
// Capital name is: Abuja
// Capital name is: Ankara
// Capital name is: Accra

Conclusion

There are several other things we can do with Dictionaries. We may have to go through Apple’s documentation on Dictionaries to see them. We may want to check out the removeValue(forKey:) property, which is used to remove a key-value pair from a Dictionary as an alternative to setting a value to nil. There is also an interesting boolean property, isEmpty, that you may want to check out. This one returns true if the Dictionary is empty, and false if the Dictionary is not empty.

Copyright ©2024 Educative, Inc. All rights reserved