TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.