Swift Tutorials: repeat-while Loop

beginner
24 min

Swift Tutorials: repeat-while Loop

Welcome to CodeYourCraft's comprehensive Swift Tutorials! Today, we're diving into the repeat-while loop, a powerful control flow statement that helps you write efficient and clean Swift code. šŸŽÆ

What is a repeat-while Loop?

The repeat-while loop is a type of loop in Swift that first executes the loop body and then checks the condition. If the condition is true, the loop continues; otherwise, it stops. This loop is useful when you want to ensure that a specific action is performed at least once, and then repeated based on a condition. šŸ“

Syntax

Here's the basic syntax of a repeat-while loop in Swift:

swift
repeat { // loop body // update your condition here } while condition

Example 1: Simple Counter

Let's create a simple counter that counts from 1 to 10 using a repeat-while loop.

swift
var counter = 1 repeat { print(counter) counter += 1 } while counter <= 10

šŸ’” Pro Tip: Use counter += 1 instead of counter = counter + 1 to make your code more concise and easier to read.

Example 2: User Input Validation

In this example, we'll use a repeat-while loop to validate user input. Our goal is to get an integer number between 1 and 100.

swift
var input: Int? repeat { print("Enter a number between 1 and 100:") if let userInput = readLine(), let num = Int(userInput) { if num >= 1 && num <= 100 { input = num break } else { print("Invalid input! Please try again.") } } else { print("Invalid input! Please try again.") } } while input == nil

In this example, the loop will continue asking the user for input until a valid number between 1 and 100 is entered. āœ…

Quiz

Quick Quiz
Question 1 of 1

What is the purpose of the `repeat-while` loop in Swift?

That's it for our introduction to the repeat-while loop in Swift! As you continue to practice, you'll discover even more ways to use this powerful control flow statement to create dynamic and efficient code. Happy coding! 😊