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

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

3      

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

3      

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.

3      

@daa  

Now I see more clearly. Thank you @roosterboy.

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.