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 dictionayvar techGiants = ["G" : "Google","N" : "Netflix","Ap" : "Apple","Am" : "Amazon","M" : "Meta"]// get the string representationslet stringified = techGiants.description// print string contentsprint(stringified)// check typeprint(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 calledstringified. - Line 17: We get the result instance type using the
type(of:)method. We then print the value to the console.