Open In App

How to remove all the elements from the Set in Swift?

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A set is a generic unordered collection that is used to store values of the same type. It means you are not allowed to keep different types in the set or we can say that a string type of set can only store string data types, not int type. You can use a set instead of an array if the order of the values is not defined or you want to store unique values. It doesn’t keep duplicate values, it always keeps unique values in it. It generally uses a hash table to store the elements. A set can be mutable or immutable. In Set, we can remove all the values from the set using the removeAll() function. This function is used to remove all the values from the specified set. It does not take any parameters.

Syntax:

setName.removeAll()

Here, 

setName is the object of the set class.

Return Value: It will remove all the elements from the specified set.

Example 1:

Swift




// Swift program to remove all the elements from the set
import Swift
  
// Creating a set of Author's name
// Here the set is of string type
var AuthorName: Set = ["Pihu", "Punit", "Sumit", "Rahul", "Mira"]
  
// Displaying original set
print("Original Set:", AuthorName)
  
// Removing all the elements
// Using removeAll() function
var result = AuthorName.removeAll()
  
// Displaying the set after removing an element
print("Final Set:", AuthorName)


Output:

Original Set: ["Rahul", "Mira", "Pihu", "Sumit", "Punit"]
Final Set: []

Example 2:

Swift




// Swift program to remove all the elements from the set
import Swift
  
// Creating a set of Authors rating
// Here the set is of float type
var AuthorRating: Set = [2, 458, 65, 8, 76, 4, 982, 3, 4, 5]
  
// Displaying original set
print("Original Set:", AuthorRating)
  
// Remove all the elements from the set
// Using removeAll() function
var result = AuthorRating.removeAll()
  
// Displaying the set after removing an element
print("Total number of elements in the AuthorRating set:", AuthorRating.count)


Output:

Original Set: [2, 65, 458, 8, 76, 982, 3, 5, 4]
Total number of elements in the AuthorRating set: 0


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads