C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Count: This returns 3, the number of elements retained in the set. The duplicate element is not counted.
Print: We use this func to display the elements present. This is a useful debugging technique.
Swift program that uses set
// Create a set and add Strings to it.
var animals = Set<String>()
animals.insert("cat")
animals.insert("bird")
animals.insert("dog")
animals.insert("dog")
// Only unique elements are stored in the set.
print(animals.count)
// The second dog element is not present.
print(animals)
Output
3
["bird", "cat", "dog"]
Swift program that uses remove, contains
var knownIds = Set<Int>()
knownIds.insert(100)
knownIds.insert(200)
knownIds.insert(300)
// Remove this Int from the set.
knownIds.remove(200)
// This is contained within the set.
if knownIds.contains(100) {
print(true)
}
// Not contained.
if !knownIds.contains(200) {
print(false)
}
Output
true
false
Swift program that uses for-in loop
var languages = Set<String>()
languages.insert("Swift")
languages.insert("Python")
languages.insert("Ruby")
// Loop over all elements in the set.
// ... Ordering is not maintained.
for language in languages {
print(language)
}
Output
Python
Ruby
Swift
Intersection: We call intersection to find the elements that are present in both sets (that intersect). A new set is returned.
Subtract: This removes elements from one set that are present in another. It modifies the first set in-place.
Swift program that uses set initializer, intersect, subtract
let colors1: Set<String> = ["red", "orange", "pink"]
let colors2: Set<String> = ["blue", "red", "pink"]
// Intersection returns a set of the two shared Strings.
// ... Red and pink are shared.
let intersection = colors1.intersection(colors2)
print(intersection)
// Subtract removes shared values.
// ... Red and pink are removed in the set.
// ... The colors1 set is modified in-place.
colors1.subtract(colors2)
print(colors1)
Output
["pink", "red"]
["orange"]