Swift--Dictionary
1. Create an empty dictionary
Way One:
var dic1 = [int:string] () the type of the//key is Int and the type of value is String
Way two:
var dic2 = dictionary<sting,int> ()//key is of type Sting
2. Create a dictionary with literal amounts
var dic3:dictionary<int,string> = [1: "A", 2: "B", 3: "C"]
3. Get the number of elements
Print (Dic3.count)
4. Is the empty
Print (Dic3.isempty)
5. Get the value
Print (dic3[2]!) ! Convert optional Types
6. Change the value
DIC3[2] = "ABC"
7. Delete a value
Way One:
DIC3[2] = nil//Because the element in the dictionary is an optional type, it can be nil directly
Way two:
Dic.removevalueforkey (2)
8. Traversing a dictionary
Way One:
For KV in dic3{
Print (KV)//Tuple format:(1, "a")
}
Way two:
for (Mkey,mvalue) in dic3{
Print (Mkey,mvalue)
}
9. Ordered output of the dictionary (small-to-large)
For key in Dic3.keys.sort () {
Print (Key,dic3[key])
}
Swift--Dictionary