Dictionaries[iOS] in swift 4. How to Use Dictionaries in Swift 4.0 - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

23 Aug 2017

Dictionaries[iOS] in swift 4. How to Use Dictionaries in Swift 4.0

Dictionary is one of the important collection type. We use dictionaries in most of apps for storing and organizing data.

Dictionary is an unordered collection of key-value pairs. Its also called as hashes or associated arrays in  other languages. 

Dictionaries flow chart image in ios - swift 4
 

Syntax :

[Key: Value] // key must be unique of same type

Example :

var blogDict = [
    "name"  : "iOS Revisited",
    "id" : "111",
    "url": "http://iosrevisited.blogspot.com",
    "description": "A blog about ios tutorials."
]

Each element is associated with a unique key. We can access elements from dictionary fast using unique keys.

Creating/Initializing Dictionary :

As arrays we can create empty dictionaries using initializers.

Syntax :

var someDict = [someKey: someValue]()

Example :

var responseMessages = [Int: String]()

// or

var responseMessages: [Int: String] = [:]

// responseMessages is an empty dictionaties of type [Int: String]

The keys are of Int type and values are of String type for responseMessages Dictionary.

Storing objects in Dictionary :

For storing values in dictionary we use subscripts as arrays.

Example :

responseMessages[400] = "Bad request" // stored value as string
responseMessages[403] = "Access forbidden"

Now responseMessages contains two objects with key 400 and 403.

Accessing and Modifying a Dictionary :

You access and modify a dictionary through its methods and properties, or by using subscript syntax.

As with an array, you find out the number of items in a Dictionary by checking its read-only count property.
print("The responseMessages dictionary contains \(responseMessages.count) items.")
// Prints "The responseMessages dictionary contains 2 items."

For checking whether dictionary is empty or not, we can use count = 0 or use the Boolean isEmpty property as a shortcut.
if responseMessages.isEmpty {
    print("The responseMessages dictionary is empty.")
} else {
    print("The responseMessages dictionary is not empty.")
}
// Prints "The responseMessages dictionary is not empty."

Here again adding two more element to responseMessages Dict.
responseMessages[500] = "Internal server error"
responseMessages[200] = "Success"
// the responseMessages dictionary now contains 4 items

For updating or modifying a value we can use subscripts as follows:
responseMessages[500] = "Something went wrong.."
// the value for "500" has been changed to "Something went wrong.."

As an alternative to subscripting for updating or modifying a value we have inbuilt functions updateValue(_:forKey:) to set or update the value for a particular key.

The updateValue(_:forKey:) method returns an optional value of the dictionary’s value type. For a dictionary that stores String values, for example, the method returns a value of type String?, or “optional String”. This optional value contains the old value for that key if one existed before the update, or nil if no value existed:
if let oldValue = responseMessages.updateValue("Access granted", forKey: 403) {
    print("The old value for 403 was \(oldValue).")
}
// Prints "The old value for 403 was Access forbidden."

Removing/Deleting object from Dictionary :

For deleting key-value pair from dictionary we can use subscripts by assigning to nil.
// "Access granted" is not the real response for 403, so delete it
responseMessages[403] = nil
// 403 has now been removed from the dictionary

Alternatively, remove a key-value pair from a dictionary with the removeValue(forKey:) method. This method removes the key-value pair if it exists and returns the removed value, or returns nil if no value existed:
if let removedValue = responseMessages.removeValue(forKey: 500) {
    print("The removed responseMessage name is \(removedValue).")
} else {
    print("The responseMessages dictionary does not contain a value for 500.")
}
// Prints "The removed responseMessage name is Internal server error"

Iterating Over a Dictionary :

As like arrays, we can iterate over the key-value pairs in a dictionary with a for-in loop.

Each item in the dictionary is returned as a (key, value) tuple, and you can decompose the tuple’s members into temporary constants or variables as part of the iteration:
for (responseCode, message) in responseMessages {
    print("\(responseCode): \(message)")
}
// 400: Bad request
// 200: Success

You can also retrieve an iterable collection of a dictionary’s keys or values by accessing its keys and values properties:
for responseCode in responseMessages.keys {
    print("response code: \(responseCode)")
}
// response code: 400
// response code: 200

for message in responseMessages.values {
    print("message: \(message)")
}
// message: Bad request
// message: Success

Convert to Arrays :

If you need to use a dictionary’s keys or values with an API that takes an Array instance, initialize a new array with the keys or values property:
let responseCodes = [Int](responseMessages.keys)
// [400, 200]
let messages = [String](responseMessages.values)
// [Bad request, Success]

Swift’s Dictionary type does not have a defined ordering. To iterate over the keys or values of a dictionary in a specific order, use the sorted() method on its keys or values property.

No comments:

Post a Comment

Post Top Ad