A dictionary stores data in the form of a key-value pair.
The key cannot be duplicated, but the value can be repeated.
Basic syntax Use cases:
var states:dictionary<string, string> = ["CA""California" = [ "CA""California"]
You can also use type inference in the following ways:
var states = ["CA":"California"]var states= ["CA":"California","NV":"Nevada","OR":"Oregon","AZ":"Arizona"]
To modify a key value:
states["NV""Nevada"
Or
States.updatevalue ("State ofNevada""NV")
Access key value:
Let value = states["NV"]
To delete a key value:
states["TX"] = nil// or states.removevalueforkey ( " TX ")
To traverse a key-value pair:
//iterate keys and values for(Key, value)inchStates {print ("state name = \ (value), abbreviation = \ (key)")}//Iterate Keys forAbbreviationinchStates.keys {print ("abbreviation = \ (abbreviation)")}//Iterate Values forNameinchstates.values {print ("name = \ (name)")}
Swift Language Essentials-Dictionary (dictionary)