{

Convert Dictionary to Array of keys and values example in swift


This tutorial explains how to convert key and value arrays from a dictionary in Swift.

Dictionary is a type that stores the key and values of a given type.

It is similar to Hashtable in storing keys and values in java.

Dictionary is unordered, so the output of keys and values in an array are unordered.

In Swift, there are two types for storing key and value pairs.

Dictionary: It is a struct that contains a specific type in swift language. NSDictionary: It is a class that is without type in Objective C

Both are used and work the same way.

Convert Dictionary keys to Array of values in swift?

  • using keys property Dictionary provides a keys method that returns all keys, these values pass to the Array constructor to return an array of keys.

Here is an example of Convert Dictionary of keys into an array

let emp: [Int: String] = [1: "john", 2: "franc", 3: "andrew"]

print(emp)
var keyArray=Array(emp.keys);
print(keyArray)

Output:

[2: "franc", 3: "andrew", 1: "john"]
[2, 3, 1]

You can also use for -in the loop to iterate and add keys to an array. First, create an Array int for holding key values. Iterate map using key and value pair syntax in for in loop adds each value to an array using an array append method

var keyArray = [Int]()

for (key, _) in emp {
    keyArray.append(key)
}
print(keyArray)

Convert Dictionary Values to Array of values in swift?

  • using values property Dictionary provides values method which passes to Array constructor to return an array. Here is an example of Convert Dictionary of values into an array
let emp: [Int: String] = [1: "john", 2: "franc", 3: "andrew"]

print(emp)
var valueArray=Array(emp.values);

print(valueArray)

Output:

[2: "franc", 3: "andrew", 1: "john"]
["franc", "andrew", "john"]
  • using append and for-in loop You can also use a for-in loop to iterate and add values to an array. First, create an Array of String types for holding dictionary values. Iterate map using key and value pair syntax in for in loop add each value to an array
var valueArray = [String]()

for (_, value) in emp {
    valueArray.append("\(value) ")
}
print(valueArray)

Conclusion

Learned multiple ways to convert Dictionary into an array of keys and values using keys and values property, for-in loop with Array append method.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.