How to remove first element from the Set in Swift?
Last Updated :
02 Jun, 2022
In Swift, a set is a generic collection that is used to store unordered 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 easily remove the first element using the removeFirst() function. This function is used to remove the very first element of the set. As we know that a set is an unordered collection so a random element is removed and returned. This function removes one element at a time. It does not take any parameters.
Syntax:
setName.removeFirst()
Here,
setName is the object of the set class.
Return Value: It will return the removed element from the set.
Example 1:
Swift
import Swift
var AuthorRating: Set = [2, 458, 65, 8, 76, 4, 982, 3, 4, 5]
print ( "Original Set:" , AuthorRating)
var result = AuthorRating.removeFirst()
print ( "Final Set:" , AuthorRating)
|
Output:
Original Set: [76, 458, 2, 5, 982, 4, 3, 8, 65]
Final Set: [458, 2, 5, 982, 4, 3, 8, 65]
Example 2:
Swift
import Swift
var AuthorName: Set = [ "Pihu" , "Punit" , "Sumit" , "Rahul" , "Mira" ]
print ( "Original Set:" , AuthorName)
var result = AuthorName.removeFirst()
print ( "Final Set:" , AuthorName)
print ( "Removed name:" , result)
|
Output:
Original Set: ["Punit", "Rahul", "Pihu", "Mira", "Sumit"]
Final Set: ["Rahul", "Pihu", "Mira", "Sumit"]
Removed name: Punit
Share your thoughts in the comments
Please Login to comment...