How to get a set as a string in Swift
Overview
A set is a sequence or a collection of unique elements. We can get a set as a string in Swift by using the debugDescription property. This is very useful when there is a need for debugging.
Syntax
set.debugDescription
Syntax for getting a set as a string in Swift
Return value
This property returns a string. This string is a representation of the set instance.
Code example
// Creating some setslet evenNumbers : Set = [10, 2, 6, 8, 4]let oddNumbers : Set = [11, 5, 7, 3, 9]let first_names : Set = ["john", "jane", "henry", "mark"]// Getting the instance typesprint(type(of: evenNumbers))print(type(of: oddNumbers))print(type(of: first_names))// Getting the sets as stringslet str1 = evenNumbers.debugDescriptionlet str2 = oddNumbers.debugDescriptionlet str3 = first_names.debugDescription// Printing the string values and typesprint(str1 + " =" , type(of:str1))print(str2 + " =" , type(of:str2))print(str3 + " =" , type(of:str3))
Explanation
- Lines 2–4: We create some sets.
- Lines 7–9: We print out the instance types of the sets.
- Lines 12–14: We get the string representations of the sets using the
debugDescriptionproperty. - Lines 17–19: We print the string representations to the console with their instance types.