[Swift Apple ] 9. Playing with Conditions


🎲 9. Playing with Conditions (if statements)





Hello again! 😊Today, we’re going to learn about one of the most important tools in coding:

Conditional statements — also known as if statements.


An if statement lets you tell Swift:


“If something is true, do this. Otherwise, do something else!”


Just like how we talk in real life!




🧠 Reacting Differently Based on a Condition


With an if statement, you can make your program do different things depending on the situation.


For example:

“If the score is 90 or higher, show ‘Excellent!’”

“Otherwise, show ‘Good job!’”


That’s how a computer makes decisions using if.


Basic structure:

if condition {
    // do this if the condition is true
} else {
    // do this if the condition is false
}






🧪 Practice: Print a Message Based on Score


Let’s try writing a simple program that shows a message based on a test score!

let score = 85

if score >= 90 {
    print("Excellent! Great job! 🎉")
} else if score >= 70 {
    print("Nice work! Keep it up! 😊")
} else {
    print("Good try! You can do even better! 💪")
}




Output:

Nice work! Keep it up! 😊

Since score is 85, it matches the second condition score >= 70, so that message is shown!






🔍 What do if, else if, and else mean?

  • if → run this code if the condition is true

  • else if → if the first condition is false, check another condition

  • else → if none of the conditions are true, run this part instead


You can check for many situations using this structure!





💡 Challenge: Special Message for a Perfect Score


Can you write code that shows a special message

only when the score is exactly 100?


Hint:

if score == 100 {
    print("Perfect score! Amazing! 🏆")
} else {
    print("Great effort! Try for a perfect score next time! 💪")
}
💡 == means “is equal to” in Swift. Be careful not to use just one =!





 

✨ Wrapping Up


Today, we learned how to use if statements in Swift!

  • if helps your program make decisions

  • You can do different things depending on the value

  • Great for creating smart, interactive apps!


In the next lesson, we’ll learn about functions,


댓글 쓰기