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. šÆ
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. š
Here's the basic syntax of a repeat-while loop in Swift:
repeat {
// loop body
// update your condition here
} while conditionLet's create a simple counter that counts from 1 to 10 using a repeat-while loop.
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.
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.
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 == nilIn this example, the loop will continue asking the user for input until a valid number between 1 and 100 is entered. ā
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! š