Activity 1
Describe a password state
Use if/else if/else to return Weak, Acceptable, or Strong based on a password length you define.
Hint: Arrange branches from the most specific threshold to the fallback.
Swift Fundamentals
Direct program behavior with if, else, guard, and exhaustive switch statements.
Before you begin
Learning stage
Conditional statements choose which code should run. Use if when behavior depends on a Boolean expression, and add else or else if branches when alternatives matter.
Use guard to require a condition and leave the current scope when it fails. Use switch when one value should be matched against several exhaustive patterns or cases.
Learning stage
The function validates progress with guard and then uses switch to create a readable category.
func progressMessage(percent: Int) -> String {
guard (0...100).contains(percent) else {
return "Invalid progress"
}
switch percent {
case 100:
return "Complete"
case 75..<100:
return "Almost there"
case 1..<75:
return "Keep going"
default:
return "Ready to begin"
}
}
print(progressMessage(percent: 82))Learning stage
These concepts appear throughout production iOS code. Focus on the requirement each technique communicates.
Learning stage
Notice these mistakes early so the compiler and type system can help instead of becoming obstacles.
Learning stage
Work through these activities in a small Xcode project. No embedded playground is required on this site.
Activity 1
Use if/else if/else to return Weak, Acceptable, or Strong based on a password length you define.
Hint: Arrange branches from the most specific threshold to the fallback.
Activity 2
Sketch an enum with loading, empty, content, and failure cases, then write a switch that returns a message for each.
Hint: Avoid default so the compiler checks exhaustiveness.
Learning stage
Answer each question before revealing the explanation.
QUESTION 1
They must be exhaustive
Every possible input must be handled, either through explicit cases or a suitable default.
QUESTION 2
It must transfer control out of the guard statement's enclosing scope, such as with return, throw, break, or continue.
Learning stage
Explain the idea in terms of its purpose, behavior, and tradeoffs rather than reciting syntax.
Short answer: Use switch when matching one value against several exhaustive patterns or enum cases.
if is flexible for unrelated Boolean conditions. switch is clearer for a single subject with multiple cases and lets the compiler verify exhaustiveness, especially for enums. It also supports ranges, tuples, value binding, and where clauses.
Possible follow-ups
Learning stage
Control flow should make the successful path and alternatives obvious. Use guard for requirements, if for general conditions, and switch for exhaustive value matching.