Iterating Over Strings P1
Part of the Fundamentals section of Coddy's Swift journey — lesson 71 of 86.
Just like arrays, strings in Swift are sequences of characters that you can iterate over. This makes it easy to process text one character at a time using the familiar for-in loop.
When you loop through a string, Swift gives you each character in order:
let word = "Hello"
for char in word {
print(char)
}
// H
// e
// l
// l
// oEach char in the loop is of type Character, not String. This distinction matters when you need to compare or manipulate individual characters.
You can use this technique to analyze text, such as counting specific characters:
let message = "banana"
var countA = 0
for char in message {
if char == "a" {
countA += 1
}
}
print(countA) // 3Notice that when comparing a character, we use a single character in quotes like "a". Swift automatically treats this as a Character when comparing with another character.
Challenge
EasyWrite a function countVowels that takes text and returns the total count of vowels in the string.
Iterate through each character in the string and count how many are vowels (a, e, i, o, u). Count both lowercase and uppercase vowels.
Parameters:
text(String): The string to analyze
Returns: The total number of vowels found in the string (Int)
Example: If text is "Hello World", the function should return 3 (the vowels are e, o, o).
Cheat sheet
You can iterate over a string using a for-in loop to process each character:
let word = "Hello"
for char in word {
print(char)
}
// H
// e
// l
// l
// oEach char in the loop is of type Character, not String.
You can compare characters directly in conditions:
let message = "banana"
var countA = 0
for char in message {
if char == "a" {
countA += 1
}
}
print(countA) // 3Try it yourself
func countVowels(text: String) -> Int {
// Write code here
}
This 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