NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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 Fernando Olivares

SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.

Try the book!

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.