Arrays are type of object that used to store group of same type of elements with fixed size of length.

Swift Dictionary type

Dictionary contains key and values of collections.

  • Order is not guaranteed in key and values.
  • Each value is mapped with unique keys
  • Used to quickly lookup the values with key

Create Empty Dictionary

Dictionary can be created empty as given below It contains key and value types with empty braces.

var dict = [String: String]()
var employes = Dictionary<Int, String>()

print(dict)
print(employes)

Output:

[:]
[:]

Declare and initialize dictionary with literal in swift?

Add key and values to dictionary in swift?

key and values can be added with below syntax. Syntax

dictionary[key]=value

key is an value of type data and value is data that stored to dictionary. Key does not allow duplicate.

Here is an example

var dict = [String: String]()
dict["1"]="One"
dict["2"]="Two"
dict["3"]="Threee"
dict["4"]="four"
dict["4"]="five"

print(dict)

How to iterate key and values of dictionary in swift?

Dictionary can be iterated using for loop.

It iterates each element that contains key and values.

var employes = Dictionary<Int, String>()
employes[1]="john";
employes[2]="Rob";
employes[3]="Eric";
employes[4]="Andrew";
employes[5]="Mark";
print(employes)
// iterate key and values of dictionary
for (key, value) in employes {
  print("\(key) : \(value)")
}

Output:

[1: "john", 2: "Rob", 3: "Eric", 5: "Mark", 4: "Andrew"]
1 : john
2 : Rob
3 : Eric
5 : Mark
4 : Andrew

How to iterate and loop dictionary keys only in swift?

dictionary.keys returns keys of an sequence. You can use forEach function for each element of an key sequence.

//Iterate keys
employes.keys.forEach { key in
     print(key)                

}

Output:

1
2
3
5
4

How to iterate and loop dictionary values only in swift?

Dictionary values can be iterate in two values

  • one approach is to use dictionary values and call forEach function
  • for loop to iterate values sequence
//Iterate values
employes.values.forEach { value in
     print(value)
}
for employee in employes.values{
  // do something with your sb item..
  print(employee)
}

Output:

john
Rob
Eric
Mark
Andrew
john
Rob
Eric
Mark
Andrew