Arrays are types of objects that are used to store groups of the same type of elements with fixed sizes of length.

Swift Dictionary type

The dictionary contains the key and values of collections.

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

Create Empty Dictionary

The 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 keys and values to the dictionary in swift?

key and values can be added with the below syntax. Syntax

dictionary[key]=value

key is a value of type data and value is data that is stored in the dictionary. The key does not allow duplicates.

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 the key and values of the dictionary in Swift?

The dictionary can be iterated using for loop.

It iterates each element that contains keys 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 return keys of a sequence. You can use forEach function for each element of a 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 iterated into two values

  • one approach is to use dictionary values and call forEach a 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