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 String contains()
In this tutorial, you will learn about the Swift contains() method with the help of examples.
The contains() method checks whether the specified string (sequence of characters) is present in the string or not.
Example
var message = "This is Swift Programming"
// check if message contains "Swift"
var result = message.contains("Swift")
print(result)
// Output: true
contains() Syntax
The syntax of the String contains() method is:
string.contains(char: charSequence)
Here, string is an object of the String class.
contains() Parameters
The contains() method takes a single parameter.
- char (charSequence) - a sequence of characters
Note: A charSequence is a sequence of characters such as String.
contains() Return Values
contains() returns
- true - if the string contains the specified character sequence
- false - if the string doesn't contain the specified character sequence
Example 1: Swift String contains()
var message = "Swift Programming Language"
// check if message contains "Swift"
var result = message.contains("Swift")
print(result) // true
// check if message contains "Java"
result = message.contains("Java")
print(result) // false
// check if message contains " "
result = message.contains(" ");
print(result) // true
Output
true false true
Here, message.contains(" ") returns true because the empty string is a subset of every other string.
Example 2: Using contains() With if...else
var message = "Swift Programming Language"
var msg1 = "Swift"
var msg2 = "swift"
// true because message contains "Swift"
if (message.contains(msg1)) {
print(message + " contains " + msg1)
}
else {
print(message + " doesn't contain " + msg1)
}
// contains() is case-sensitive
// false because message doesn't contains "swift"
if (message.contains(msg2)) {
print(message + " contains " + msg2)
}
else {
print(message + " doesn't contain " + msg2)
}
Output
Swift Programming Language contains Swift Swift Programming Language doesn't contain swift
Did you find this article helpful?