Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Swift Set contains()
In this tutorial, we will learn about the Swift Set contains() method with the help of examples.
The contains() method checks whether the specified element is present in the set or not.
Example
var languages: Set = ["Swift", "C", "Java"]
// check if languages contains "Swift"
var result = languages.contains("Swift")
print(result)
// Output: true
contains() Syntax
The syntax of the set contains() method is:
set.contains(obj)
Here, set is an object of the set class.
contains() Parameters
The contains() method takes a single parameter:
- obj - element to be checked for its presence in the set
contains() Return Values
The contains() method returns:
- true - if the set contains the specified element
- false - if the set doesn't contain the specified element
Example 1: Swift String contains()
var names: Set = ["Gregory", "Perry", "Nadal"]
// check if names contains "Nadal"
var result = names.contains("Nadal")
print(result)
// check if message contains "Federer"
result = names.contains("Federer")
print(result)
Output
true false
In the above example,
"Nadal"is present in the set, so the method returnstrue."Federer"is not present in the set, so the method returnsfalse.
Example 2: Using contains() With if...else
var names: Set = ["Gregory", "Perry", "Nadal"]
var name1 = "Gregory"
var name2 = "gregory"
// true because names contains "Gregory"
if (names.contains(name1)) {
print( "set contains", name1)
}
else {
print("set doesn't contain", name1)
}
// contains() is case-sensitive
// false because names doesn't contains "gregory"
if (names.contains(name2)) {
print( "set contains", name2)
}
else {
print( "set doesn't contain", name2)
}
Output
set contains Gregory set doesn't contain gregory
Did you find this article helpful?