UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 12: Optionals: "Unwrapping with Guard"

Forums > 100 Days of SwiftUI

@Caleb  

Hello. In one of Paul's Review Quiz questions and the result is that it is "valid Swift".

I don't know what "return" is doing in this example. Is this shorthand for "return nil"?

func test(number: Int?) {
  guard let number = number else
  { return }
    print("Number is \(number)")
   }
   test(number: 42)

3      

Return exits the function early

3      

@Caleb  

"Return exits the function early". Okay, got it.

What would happen in the funcion if the integer was nil?

test(number: nil)

3      

Exactly that! The function will be exited early in the guatd statement, meaning the rest of the function isn't executed. So in this case, the print statement will not be run!

3      

your function returns void i.e. nothing. guard statements is there to check if its nil or not. if var provided is nil then else block of the guard statement is executed. and there you wrote return which means just return from the function without trying to do anything else.

3      

Hacking with Swift is sponsored by RevenueCat

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

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.