Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
set
string
communitycreator

How to get a set as a string in Swift

Theodore Kelechukwu Onyejiaku

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 sets
let 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 types
print(type(of: evenNumbers)) 
print(type(of: oddNumbers)) 
print(type(of: first_names)) 

// Getting the sets as strings
let str1 = evenNumbers.debugDescription
let str2 = oddNumbers.debugDescription
let str3 = first_names.debugDescription

// Printing the string values and types
print(str1 + " =" , type(of:str1))
print(str2 + " =" , type(of:str2))
print(str3 + " =" , type(of:str3))
Getting a set as a string in Swift

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 debugDescription property.
  • Lines 17–19: We print the string representations to the console with their instance types.

RELATED TAGS

swift
set
string
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring