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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out 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.