Swift Set – Remove
Furthermore, if you want to know the element that is removed from the swift set, you can store the element in a variable and unwrap it using “!”.
Syntax:
Where the swift_set is the set and element is the value/string to be removed from the swift_set.
Example 1:
Let’s create a Swift set with Integer type and remove an element.
var swift_set1:Set<Int> = [100,200,300,400,56]
print("Actual Set - \(swift_set1)")
//remove element-100
var r1 = swift_set1.remove(100)
print("Final Set - \(swift_set1)")
//display the removed element
print("Removed Element is - \(r1!)")
Output:
Explanation:
Line 2:
Swift_set1 has 5 integer elements.
Line 7:
Using the remove() method, we remove the element 100 and store that removed element in the r1 variable.
Line 9:
We display the final set. Now, the remaining elements are displayed.
Line 12:
Finally, we display the removed element through ”!”.
Example 2:
Let’s create a Swift set with Double type and remove an element.
var swift_set1:Set<Double> = [9.1,9.2,9.300,9.67,9.34,6.78]
print("Actual Set - \(swift_set1)")
//remove element-9.67
var r1 = swift_set1.remove(9.67)
print("Final Set - \(swift_set1)")
//display the removed element
print("Removed Element is - \(r1!)")
Output:
Explanation:
Line 2:
Swift_set1 has 6 numeric elements of Double type.
Line 7:
Using the remove() method, we remove the element 9.67 and store that removed element in the r1 variable.
Line 9:
We display the final set. Now, the remaining elements are displayed.
Line 12:
Finally, we display the removed element through ”!”.
Example 3:
Let’s create a Swift set with String type and remove the elements.
var swift_set1:Set<String> = ["swift1","swift2","swift3"]
print("Actual Set - \(swift_set1)")
//remove element-"swift1"
swift_set1.remove("swift1")
print("After removing swift-1 - \(swift_set1)")
//remove element-"swift3"
swift_set1.remove("swift3")
print("After removing swift-3 - \(swift_set1)")
Output:
Explanation:
Line 2:
Swift_set1 has 3 strings.
Line 7:
Using the remove() method, we remove the “swift1”.
Line 12:
Using the remove() method, we remove the “swift3”.
Now, if we display the set, only the “swift-2” is left.
Conclusion
The remove() method in swift set is used to remove a particular element from the given set. If you want to know the element that is removed from the swift set, you can store the element in a variable and unwrap it using “!”. We discussed the three examples of different data types to understand this concept better.
Source: linuxhint.com