NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

SOLVED: 100days Challenge: Output between function call via a variable and direct function call are different.

Forums > Swift

@daa  

Why are the results different? Calling this function via a variable produces the predicted output, calling the function directly returns the closure. It is not life-threatening, but maybe it helps me to understand the basic concepts better.

func swingBat() -> () -> Void {
    var swingCount = 0
    return {
        if swingCount >= 3 {
            print("You're out!")
        } else {
            print("Strike \(swingCount + 1)")
        }
        swingCount += 1
    }
}
let swing = swingBat()
swing()
swing()
swing()
swing()
swingBat()
swingBat()
swingBat()
swingBat()

screenshot

   

@daa  

Maybe I figured it out myself.

swing is just a variable that holds a function

swing() calls than actually the assigned function and let it do its processing.

similar:

swingBat() is the function itself (swingBat().self)

to let actually do the functions its work I have to call it like this: swingBat()() – allthough it's a bit strange looking for me it does the job

Bildschirmfoto-2020-04-13-um-14-47-14.png

Maybe this is an explanation that makes some sense.

Any ideas?

Thank you.

   

swingBat() is the function itself (swingBat().self)

Not quite. It returns a function that you can then call by appending an additional set of (). So by calling swingBat() you get back a function; by calling swingBat()() you get back a function and then immediately call that function.

   

@daa  

Now I see more clearly. Thank you @roosterboy.

   

Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

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

Not logged in

Log in
 

Link copied to your pasteboard.