Swift – Dictionary to Arrays of Keys and Values

Welcome to Swift Tutorial. In our previous tutorial, we learned how to create a dictionary using arrays. In this tutorial, we will go the way around and learn how to convert a Swift Dictionary into Arrays.

To convert a dictionary into arrays of keys and values, use the methods dictionary.keys and dictionary.values.

</>
Copy
var myDictionary:[keyType:valueType] = [key1:value1, key2:value1]

var keys = myDictionary.keys
var values = myDictionary.values

The type of keys array is same as that of keyType, and the type of values array is same as that of valueType.

Example 1 – Get Key and Value arrays from Swift Dictionary

In this example, we will create a dictionary with some initial values, and extract the arrays with keys and values separately.

main.swift

</>
Copy
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]

var keys = myDictionary.keys
var values = myDictionary.values


print("keys\n-------")
for key in keys {
   print("\(key)")
}

print("\nvalues\n-------")
for value in values {
   print("\(value)")
}

Output

keys
-------
Mohan
John
Raghu

values
-------
75
79
82

Conclusion

In this Swift Tutorial, we have learned how to convert a Swift Dictionary to Arrays of Keys and Values with the help of example programs.