Tutorial by Examples

Dictionaries are an unordered collection of keys and values. Values relate to unique keys and must be of the same type. When initializing a Dictionary the full syntax is as follows: var books : Dictionary<Int, String> = Dictionary<Int, String>() Although a more concise way of initia...
Add a key and value to a Dictionary var books = [Int: String]() //books = [:] books[5] = "Book 5" //books = [5: "Book 5"] books.updateValue("Book 6", forKey: 5) //[5: "Book 6"] updateValue returns the original value if one exists or nil. let previous...
A value in a Dictionary can be accessed using its key: var books: [Int: String] = [1: "Book 1", 2: "Book 2"] let bookName = books[1] //bookName = "Book 1" The values of a dictionary can be iterated through using the values property: for book in books.values { ...
var dict = ["name": "John", "surname": "Doe"] // Set the element with key: 'name' to 'Jane' dict["name"] = "Jane" print(dict)
let myAllKeys = ["name" : "Kirit" , "surname" : "Modi"] let allKeys = Array(myAllKeys.keys) print(allKeys)
extension Dictionary { func merge(dict: Dictionary<Key,Value>) -> Dictionary<Key,Value> { var mutableCopy = self for (key, value) in dict { // If both dictionaries have a value for same key, the value of the other dictionary is used. mu...

Page 1 of 1