How to get a Dictionary instance in the form of a string in Swift

Overview

We use the description property of a Dictionary instance to get the string representation of the contents of that Dictionary instance.

Syntax

dictionary.description

Return value

The value returned is a string. This string represents the contents of the Dictionary instance, dictionary's, entries.

Example

// create a dictionay
var techGiants = [
"G" : "Google",
"N" : "Netflix",
"Ap" : "Apple",
"Am" : "Amazon",
"M" : "Meta"
]
// get the string representations
let stringified = techGiants.description
// print string contents
print(stringified)
// check type
print(type(of: stringified)) // String

Explanation

  • Line 2: We create a dictionary called techGiants. We then populated it with some entry values.
  • Line 11: We get the dictionary’s contents in the form of a string. Then, we store the result in a variable called stringified.
  • Line 17: We get the result instance type using the type(of:) method. We then print the value to the console.

Free Resources