0
0
Swiftprogramming~10 mins

Guard for early exit pattern in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to use a guard statement that exits early if the number is not positive.

Swift
func checkNumber(_ number: Int) {
    guard [1] else {
        print("Number is not positive")
        return
    }
    print("Number is positive")
}
Drag options to blanks, or click blank then click option'
Anumber > 0
Bnumber == 0
Cnumber < 0
Dnumber >= 0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'number == 0' which allows zero as positive.
Using 'number < 0' which is the opposite condition.
2fill in blank
medium

Complete the guard statement to unwrap the optional string safely.

Swift
func greet(_ name: String?) {
    guard let unwrappedName = [1] else {
        print("No name provided")
        return
    }
    print("Hello, \(unwrappedName)!")
}
Drag options to blanks, or click blank then click option'
Aname!
BString(name)
CunwrappedName
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'name!' which force unwraps and can cause a crash.
Using 'unwrappedName' which is the new constant, not the optional.
3fill in blank
hard

Fix the error in the guard statement to check if the array is not empty.

Swift
func process(items: [Int]) {
    guard [1] else {
        print("No items to process")
        return
    }
    print("Processing \(items.count) items")
}
Drag options to blanks, or click blank then click option'
Aitems.count == 0
Bitems.isEmpty
C!items.isEmpty
Ditems.count > 0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'items.isEmpty' which exits early when array has items.
Using 'items.count == 0' which is true when empty, opposite of needed.
4fill in blank
hard

Fill both blanks to unwrap an optional integer and check it is positive.

Swift
func validate(_ value: Int?) {
    guard let number = [1], number [2] 0 else {
        print("Invalid number")
        return
    }
    print("Valid number: \(number)")
}
Drag options to blanks, or click blank then click option'
Avalue
B>
C>=
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' instead of '>' which allows zero as valid.
Using 'number' instead of 'value' to unwrap.
5fill in blank
hard

Fill all three blanks to unwrap two optionals and check the second is not empty.

Swift
func process(user: String?, email: String?) {
    guard let username = [1], let userEmail = [2], !userEmail.[3] else {
        print("Missing or empty email")
        return
    }
    print("User: \(username), Email: \(userEmail)")
}
Drag options to blanks, or click blank then click option'
Auser
Bemail
CisEmpty
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'count' instead of 'isEmpty' which requires a comparison.
Not unwrapping both optionals before checking.