Swift – Check if a Set Contains a Value
Use the Swift Set.contains(_:) method to check whether a specific value is present in a set. The method returns true when the set contains the value and false when it does not.
setName.contains(element)
The value passed to contains(_:) must have the same type as the elements stored in the set.
How Swift Set contains(_:) Works
A Swift Set stores unique values whose type conforms to Hashable. The contains(_:) method performs a membership test without changing the set.
- It returns a Boolean value.
- It does not insert or remove an element.
- String membership checks are case-sensitive.
- It is suitable for repeated membership checks when values must remain unique.
Example 1 – Check if a Number Is Present in a Swift Set
In this Swift program, we take a set of prime numbers and check if the elements 5 and 6 are present in the Set.
main.swift
let primes: Set = [2, 3, 5, 7, 11, 13]
var isElementPresent = primes.contains(5)
print("Is element (5) present: \(isElementPresent)")
isElementPresent = primes.contains(6)
print("Is element (6) present: \(isElementPresent)")
Output
Is element (5) present: true
Is element (6) present: false
The set contains 5, so the first call returns true. It does not contain 6, so the second call returns false.
Example 2 – Check if a String Is Present in a Swift Set
In this Swift program, we take a set of month names and check if the elements “January” and “Sunday” are present in the Set.
main.swift
let months: Set = ["January", "February", "March"]
var isElementPresent = months.contains("January")
print("Is element (January) present: \(isElementPresent)")
isElementPresent = months.contains("Sunday")
print("Is element (Sunday) present: \(isElementPresent)")
Output
Is element (January) present: true
Is element (Sunday) present: false
Swift Set String Checks Are Case-Sensitive
When a set contains strings, contains(_:) compares their exact values. For example, "January" and "january" are treated as different strings.
let months: Set<String> = ["January", "February", "March"]
print(months.contains("January"))
print(months.contains("january"))
Output
true
false
For a case-insensitive membership check, normalize the strings before storing and searching them.
let acceptedCommands: Set<String> = ["start", "stop", "pause"]
let userInput = "START"
let isAccepted = acceptedCommands.contains(userInput.lowercased())
print(isAccepted)
Output
true
Use contains(where:) for a Condition-Based Set Search
Use contains(where:) when you need to determine whether any set element satisfies a condition rather than matching one exact value.
let scores: Set<Int> = [42, 68, 75, 91]
let containsHighScore = scores.contains { score in
score >= 90
}
print(containsHighScore)
Output
true
The closure is evaluated until Swift finds an element that satisfies the condition. In this example, the set contains 91, which is greater than or equal to 90.
Check Whether a Swift Set Contains Multiple Values
To check whether a set contains every value from another set, use isSuperset(of:). To check whether the two sets share at least one value, use isDisjoint(with:) and negate its result.
let availablePermissions: Set<String> = ["read", "write", "share"]
let requiredPermissions: Set<String> = ["read", "write"]
let requestedPermissions: Set<String> = ["delete", "share"]
let containsAllRequired = availablePermissions.isSuperset(of: requiredPermissions)
let containsAnyRequested = !availablePermissions.isDisjoint(with: requestedPermissions)
print(containsAllRequired)
print(containsAnyRequested)
Output
true
true
Check a Value Before Inserting It into a Swift Set
You can call contains(_:) before inserting a value. However, the result returned by insert(_:) can often perform the same check and insertion in one operation.
var usernames: Set<String> = ["alex", "mira"]
if !usernames.contains("sam") {
usernames.insert("sam")
}
print(usernames.contains("sam"))
Output
true
The following version uses the Boolean value from the result of insert(_:) to determine whether the value was newly inserted.
var usernames: Set<String> = ["alex", "mira"]
let result = usernames.insert("sam")
print(result.inserted)
print(result.memberAfterInsert)
Output
true
sam
Swift Set contains(_:) and Array contains(_:)
Both Set and Array provide a contains(_:) method, but the collections have different purposes.
| Collection | Use it when | Duplicate values | Element order |
|---|---|---|---|
Set | You need unique values and frequent membership checks | Not allowed | Not guaranteed |
Array | You need an ordered sequence of values | Allowed | Preserved |
Choose a set when membership testing and uniqueness are central to the task. Choose an array when the order of elements or duplicate values must be preserved.
Common Mistakes When Checking Swift Set Membership
- Using a mismatched value type: A
Set<Int>cannot be searched using aString. - Expecting a case-insensitive String match:
"Swift"and"swift"are different values. - Using contains(_:) for a condition: Use
contains(where:)when the search depends on a predicate. - Expecting a fixed element order: A set does not guarantee iteration order.
- Using an array for repeated unique-value lookups: A set may better represent the data when order and duplicates are unnecessary.
Frequently Asked Questions About Swift Set contains(_:)
What does Set.contains(_:) return in Swift?
It returns true if the set contains the specified value. Otherwise, it returns false.
How do I check whether a Swift Set contains a String?
Pass the string to contains(_:), such as names.contains("Alex"). The comparison is case-sensitive.
How do I check whether any Set element matches a condition?
Use contains(where:) with a closure, such as numbers.contains { $0 > 100 }.
How do I check whether a Swift Set contains all required values?
Convert the required values to a set and call isSuperset(of:) on the main set.
Does contains(_:) modify the Swift Set?
No. It only checks membership and leaves the set unchanged.
Swift Set Membership Check Summary
Use set.contains(value) to test for an exact value and set.contains(where:) to test whether any element satisfies a condition. For multiple values, set relationship methods such as isSuperset(of:) and isDisjoint(with:) express the intended check more clearly.
In this Swift Tutorial, we have learned how to check if an element is present in the Set with the help of Swift example programs.
TutorialKart.com