The Contains Method
Part of the Fundamentals section of Coddy's Swift journey — lesson 76 of 86.
When working with arrays, you often need to check if a specific value exists before performing an action. Swift provides the contains() method for exactly this purpose—it returns true if the element is found, and false otherwise.
let fruits = ["apple", "banana", "orange"]
if fruits.contains("banana") {
print("We have bananas!")
}
// We have bananas!This is much cleaner than writing a loop to search through the array manually. The method works with any type of array, whether it contains strings, numbers, or other values:
let numbers = [10, 20, 30, 40, 50]
print(numbers.contains(30)) // true
print(numbers.contains(99)) // falseA common use case is validating user input against a list of allowed values:
let validOptions = ["yes", "no", "maybe"]
let userInput = "yes"
if validOptions.contains(userInput) {
print("Valid choice")
} else {
print("Invalid choice")
}
// Valid choiceThe contains() method also works with strings to check if a substring exists within a larger string:
let message = "Hello, Swift!"
print(message.contains("Swift")) // trueChallenge
EasyYou will receive two lines of input:
- A comma-separated list of allowed usernames (e.g.,
admin,user,guest,moderator) - A username to check
Check if the username exists in the allowed list. If it does, print Access granted. If it doesn't, print Access denied.
Steps:
- Read the comma-separated list and split it into an array of strings
- Read the username to check
- Use the
contains()method to determine if the username is in the allowed list - Print the appropriate message based on the result
Hint: Use components(separatedBy:) to split a string into an array. For example:
let text = "a,b,c"
let parts = text.components(separatedBy: ",")Cheat sheet
The contains() method checks if a specific value exists in an array, returning true if found and false otherwise:
let fruits = ["apple", "banana", "orange"]
if fruits.contains("banana") {
print("We have bananas!")
}
// We have bananas!It works with any array type:
let numbers = [10, 20, 30, 40, 50]
print(numbers.contains(30)) // true
print(numbers.contains(99)) // falseCommon use case for validating input:
let validOptions = ["yes", "no", "maybe"]
let userInput = "yes"
if validOptions.contains(userInput) {
print("Valid choice")
} else {
print("Invalid choice")
}
// Valid choiceThe contains() method also works with strings to check for substrings:
let message = "Hello, Swift!"
print(message.contains("Swift")) // trueTo split a string into an array, use components(separatedBy:):
let text = "a,b,c"
let parts = text.components(separatedBy: ",")Try it yourself
// Read the comma-separated list of allowed usernames
let allowedList = readLine()!
// Read the username to check
let username = readLine()!
// TODO: Write your code below
// 1. Split the allowedList into an array using components(separatedBy:)
// 2. Use contains() to check if username is in the array
// 3. Print "Access granted" or "Access denied" based on the resultThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input