Swift: Iterating Through Strings

Iterating Through Strings in Swift:

Let’s discuss iterating through strings in Swift in detail.

We can loop over strings as well as numbers! A string, after all, is a collection of characters.

Let’s say we wanted to check a string for the letter "o". That means we’d loop through the characters in a String in a program. Each iteration would include a check to see if the character was a "o".

let words = "Lines are very difficult to learn.";
for char in words {
  if char == "o" {
    print("There is an o!");

The for-in loop’s basic structure remains the same, but instead of going through each number in a range, we’re going through each character in our String.

The following is what the example above would look like printed out:

There is an o!

We can see that each character of the string words is printed out in our printout (we skipped over a few characters with a ... to lessen the amount printed). In addition, every time a character is a “o,” . The program prints There is an o!.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: