Swift Basics - Dictionaries

Dictionaries
They store key value pairs, like pupil name with pupil ID.

To create and initialise a dictionary:
var countries = ["US":"America", "IN":"India", "SG":"Singapore"]
(can use let too if it is immutable)

Declaring an empty dictionary:
var d1 = [String:String]()
var d2 = [Int:String]()
To ensure that the type can be used as a key, the type used has to be hashable.

To access the value based on the key:
var nameOfCountry = countries["SG"]

To get the count of a dictionary:
var cnt = countries.count

To check if a dictionary is empty:
var isItEmpty = countries.isEmpty

Updating the value of a key:
countries["US": "United States"]
OR
var theOriginalValue = countries.updateValue("United States", forKey:"US")

Adding a key-pair value to the dictionary:
countries["MY"] = "Malaysia"
OR
var originalValue = countries.updateValue("Thailand", forKey:"TH")
originalValue will be nil

Removing a key-pair value:
countries["IN"] = nil
OR
var originalValue = countries.removeValue(forKey: "IN")

Removing all elements in a dictionary:
countries.removeAll()

Comments

Popular posts from this blog

Setting up a playground

Go to another page