| by Arround The Web | No comments

Swift Set – removeFirst

If you are working on Swift set collections, there is a requirement—you have to remove only the first element from the Set.

removeFirst() in the Swift set deletes the first element from the Swift set and returns the deleted element. When you print the set after that, you can see that the first element is removed from the set. So, it is not required to pass any parameters through this method.

Syntax:

swift_set.removeFirst()

Where, swift_set is the set with elements.

Example 1:

Let’s create a set with integer type elements and remove the first element.

// create first swift set

var swift_set1: Set<Int> = [10,20,34,56,78]

print("Actual Set - \(swift_set1)")

//remove the first element from swift_set1

print("Removed Element - \(swift_set1.removeFirst())")

print("Final Set - \(swift_set1)")

Output:

Explanation:

Line 2:

Created a set named swift_set1 that holds 5 integer values.

Here, 20 is the first element (Since set in swift  is an unordered collection)

Line 7:

Displayed the removed first element.

Line 9:

You can see the result by displaying swift_set1.

The first element -20 is removed.

Example 2:

Let’s create a set with double type elements and remove the first element.

// create first swift set

var swift_set1: Set<Double> = [11.3,5.6,7.8,9.0,5.4]

print("Actual Set - \(swift_set1)")

//remove the first element from swift_set1

print("Removed Element - \(swift_set1.removeFirst())")

print("Final Set - \(swift_set1)")

Output:

Explanation:

Line 2:

Created a set named swift_set1 that holds 5 double values.

Here, 9.0 is the first element (since set in swift is an unordered collection).

Line 7:

Displayed the removed first element.

Line 9:

You can see the result by displaying swift_set1.

So, the first element – 9.0 is removed.

Example 3:

Let’s create a set with String type elements and remove the first element.

// create first swift set

var swift_set1: Set<String> = ["swift1","swift2","swift3","swift4"]

print("Actual Set - \(swift_set1)")

//remove the first element from swift_set1

print("Removed Element - \(swift_set1.removeFirst())")

print("Final Set - \(swift_set1)")

Output:

Explanation:

Line 2:

Created a set named swift_set1 that holds 4 strings.

Here “swift2” is the first element (since set in swift is an unordered collection).

Line 7:

Displayed the removed first element.

Line 9:

You can see the result by displaying swift_set1.

So, the first element – “swift2” – is removed.

Conclusion

In this swift guide, we saw how to remove the first element in a set using removeFirst() method. removeFirst() in the Swift set deletes the first element from the Swift set and returns the deleted element. When you print the set after that, you can see that the first element is removed from the set.

Share Button

Source: linuxhint.com

Leave a Reply