Iterating Over Strings P2
Part of the Fundamentals section of Coddy's Swift journey — lesson 72 of 86.
Just like we used enumerated() with arrays to get both the index and element, we can do the same with strings. This is useful when you need to know the position of each character while iterating.
let word = "Swift"
for (index, char) in word.enumerated() {
print("\(index): \(char)")
}
// 0: S
// 1: w
// 2: i
// 3: f
// 4: tThis technique is helpful when building new strings based on character positions. For example, you might want to keep only characters at even indices:
let text = "abcdef"
var result = ""
for (index, char) in text.enumerated() {
if index % 2 == 0 {
result += String(char)
}
}
print(result) // aceNotice that we convert char to a String using String(char) before appending it. This is necessary because result is a String, and you cannot directly append a Character to it using the += operator.
Challenge
EasyWrite a function extractOddIndexChars that takes text and returns a new string containing only the characters at odd indices.
Use enumerated() to iterate through the string and build a result containing characters where the index is odd (1, 3, 5, etc.).
Parameters:
text(String): The input string to process
Returns: A string containing only the characters at odd indices (String)
Example: If text is "abcdefg", the function should return "bdf" (characters at indices 1, 3, and 5).
Cheat sheet
Use enumerated() with strings to get both the index and character while iterating:
let word = "Swift"
for (index, char) in word.enumerated() {
print("\(index): \(char)")
}
// 0: S
// 1: w
// 2: i
// 3: f
// 4: tWhen building strings based on character positions, convert Character to String before appending:
let text = "abcdef"
var result = ""
for (index, char) in text.enumerated() {
if index % 2 == 0 {
result += String(char)
}
}
print(result) // aceUse String(char) to convert a Character to a String when appending with +=.
Try it yourself
func extractOddIndexChars(text: String) -> String {
// 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