GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: Unwrapping Optionals

Forums > 100 Days of SwiftUI

Hi, while I was testing myself (Unwrapping with guard) there was this code:

func verify(age: Int?) -> Bool {
    guard age >= 18 {
        return true
    } else {
        return false
    }
}
if verify(age: 28) {
    print("You're old enough.")
} else {
    print("Come back in a few years.")
}

which should not print anything because it's missing else keyword in the guard line (Correct! guard must be followed by else.)

But if I try to run it with the else keyword it's still showing an error (Value of optional type 'Int?' must be unwrapped to a value of type 'Int')

I've tried to fix it but I was unsuccessful.

Thank you for all the answers...

   

Maybe this sheds the light to what is going on with guard and optional?

func verify(age: Int?) -> Bool {
    // 1. if there is age, code continues to execute. guard let makes sure you check for Int being provided i.e. unwrap it
    guard let age else { return false } // <- and if there was not age you return false and stop executing the below lines of code
    // 2. so if you provided age we can continue execution of the code lines below and return true
    return true
}

   

I think the purpose of that code should be that it should return true if the age is higher or equal to 18 and false if it's lower so this doesn't work properly...

But thank you... :)

   

Well what's the problem then? Add the check after...

func verify(age: Int?) -> Bool {
    guard let age else { return false } // Check if you provided age at all
    // check if the age is under or above 18
    if age <= 18 {
        print("Come back in a few years.")
        return false
    } else {
        print("You're old enough.")
        return true
    }
}

1      

Check the 4th question and try answer it: (https://www.hackingwithswift.com/review/sixty/unwrapping-with-guard)

as being said there should be missing only the else keyword, but that's not true you have to rewrite it and put the if statement inside the function...

That's all...

I only wanted to know if I'm missing something, but thank you so much you helped me a lot. :)

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.