Skip to content
DeveloperMemos

Using `contains` in Swift

Swift, Development1 min read

The contains method in Swift is a powerful tool that allows you to check if a particular element is present in an array or a string. This method provides a concise and convenient way to perform membership tests, making your code more readable and efficient. In this article, we will explore the usage of contains in Swift with examples.

Using contains with Arrays

The contains method can be used to check if an array contains a specific element. Here's the basic syntax:

1let numbers = [1, 2, 3, 4, 5]
2let containsThree = numbers.contains(3)
3
4if containsThree {
5 print("The array contains the number 3")
6} else {
7 print("The array does not contain the number 3")
8}

In the above example, we have an array of numbers, and we use the contains method to check if the number 3 is present in the array. If the element is found, the result is true; otherwise, it's false. In this case, the output will be "The array contains the number 3."

You can also use contains with an array of strings or any other type that conforms to the Equatable protocol. The method compares the elements using the equality operator (==) to determine their equality.

Using contains with Strings

The contains method can also be used to check if a string contains a specific substring. Here's an example:

1let message = "Hello, World!"
2let containsHello = message.contains("Hello")
3
4if containsHello {
5 print("The string contains the substring 'Hello'")
6} else {
7 print("The string does not contain the substring 'Hello'")
8}

In the above example, we have a string message, and we use the contains method to check if it contains the substring "Hello." If the substring is found, the result is true; otherwise, it's false. In this case, the output will be "The string contains the substring 'Hello'."

The contains method is case-sensitive, so it will only match the exact substring. If you want a case-insensitive search, you can use the range(of:) method with the appropriate options.

Wrap Up

The contains method in Swift provides a simple and effective way to check for the presence of elements in arrays and substrings in strings. By using this method, you can write cleaner and more concise code while performing membership tests. Whether you're working with arrays or strings, the contains method is a valuable addition to your Swift programming toolkit.