0
0
Swiftprogramming~10 mins

Guard let for early exit 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 unwrap the optional value using guard let.

Swift
func printName(name: String?) {
    guard [1] = name else {
        print("No name provided.")
        return
    }
    print("Name is \(unwrappedName)")
}
Drag options to blanks, or click blank then click option'
Avar name
Blet unwrappedName
Clet name
Dvar unwrappedName
Attempts:
3 left
💡 Hint
Common Mistakes
Using var instead of let in guard let statement.
Not unwrapping the optional before use.
Trying to unwrap with the same variable name.
2fill in blank
medium

Complete the code to unwrap the optional and print the unwrapped value.

Swift
func greet(user: String?) {
    guard let name = [1] else {
        print("User not found.")
        return
    }
    print("Hello, \(name)!")
}
Drag options to blanks, or click blank then click option'
Aname
Bself.user
Cuser
DoptionalUser
Attempts:
3 left
💡 Hint
Common Mistakes
Using the unwrapped variable name on the right side instead of the optional.
Using a variable that does not exist in the scope.
3fill in blank
hard

Fix the error in the guard statement to unwrap the optional correctly.

Swift
func checkAge(age: Int?) {
    guard let age = [1] else {
        print("Age is missing.")
        return
    }
    print("Age is \(age)")
}
Drag options to blanks, or click blank then click option'
Aage
BoptionalAge
Cself.age
Dnil
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable that is not defined in the function.
Using nil instead of the optional variable.
4fill in blank
hard

Fill both blanks to unwrap the optional and check if the unwrapped value is greater than 18.

Swift
func verify(age: Int?) {
    guard [1] = age, [2] > 18 else {
        print("Access denied.")
        return
    }
    print("Access granted.")
}
Drag options to blanks, or click blank then click option'
Alet unwrappedAge
Bage
CunwrappedAge
Dlet age
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same variable name for unwrapping and condition incorrectly.
Not unwrapping before comparing.
5fill in blank
hard

Fill all three blanks to unwrap two optionals and check if the unwrapped user is a non-empty string.

Swift
func validate(user: String?, password: String?) {
    guard [1] = user, [2] = password, ![3].isEmpty else {
        print("Invalid input.")
        return
    }
    print("User and password are valid.")
}
Drag options to blanks, or click blank then click option'
Alet unwrappedUser
Blet unwrappedPassword
CunwrappedPassword
DunwrappedUser
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable names in the condition.
Not unwrapping both optionals before checking.