1. Introduction
Sets in Swift are unordered collections of unique values of the same type. Unlike arrays, sets do not retain items in a specific order, and each item can only appear once. This makes sets useful for operations like checking membership, intersection, and union.
2. Source Code Example
// Creating a set of Strings
var fruits: Set<String> = ["Apple", "Banana", "Cherry"]
// Checking if a set contains a particular item
let hasApple = fruits.contains("Apple")
// Adding a new item
fruits.insert("Date")
// Removing an item
fruits.remove("Banana")
// Merging two sets
let moreFruits: Set<String> = ["Elderberry", "Fig", "Grape"]
fruits.formUnion(moreFruits)
// Finding the intersection of two sets
let tropicalFruits: Set<String> = ["Banana", "Fig", "Mango"]
let intersection = fruits.intersection(tropicalFruits)
// Finding the symmetric difference between two sets
let difference = fruits.symmetricDifference(tropicalFruits)
// Iterating over a set
for fruit in fruits {
print(fruit)
}
Output:
Apple Date Elderberry Fig Cherry Grape
3. Step By Step Explanation
1. A Set named fruits is created with values of type String.
2. You can check whether a specific value exists in the set using the contains(_:) method.
3. The insert(_:) method is used to add a new value to the set.
4. The remove(_:) method removes an item from the set.
5. The formUnion(_:) method combines two sets, merging them into one without any duplicate values.
6. The intersection(_:) method identifies common values shared between two sets.
7. The symmetricDifference(_:) method returns the values that are either in one set or the other, but not in both.
8. You can iterate through the items in a set using a for-in loop.
Comments
Post a Comment