-3

How can i pass a function to run inside a function when passing it inside a parameter? .. as example

func thisDelay(_ passFunc:() ){//
        let seconds = 5.0
        DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
            passFunc
            print("test2")
        }

thisDelay(print("Hello"))

//..Hello (is printed right away)
//.. test2 (is printed after 5 seconds)

// As seen Hello is printed right away .. shouldn't it been delayed with 5 sec? 
 
dn70a
  • 21
  • 3
  • 1
    Passing function as a completion block will help you. like -> **(_ passFunc: @escaping () -> Void )** and then calling it inside asynAfter like **passFunc()** – Saurabh Prajapati Nov 23 '20 at 13:22
  • 1
    You are not passing a function, and `passFunc` is not typed as a function (it is a Void). Also, in `thisDelay` you are not _calling_ `passFunc`, you are just saying its name. – matt Nov 23 '20 at 16:02

1 Answers1

2

It's hard to list everything that's wrong with your code...

  • In the line thisDelay(print("Hello")), you are not passing any function. You're just printing, right then, as you call thisDelay.

  • In the declaration of thisDelay, the parameter passFunc is not typed as a function; it is a Void.

  • In the body of thisDelay, you are not calling passFunc (which you cannot do in any case, as it is not a function); you are just saying its name, which is useless.

You probably mean something like this:

func thisDelay(_ passFunc: @escaping () -> ()) {
    let seconds = 5.0
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
        passFunc()
        print("test2")
    }
}
thisDelay { print("Hello") }
matt
  • 447,615
  • 74
  • 748
  • 977
  • But for a _real_ `delay` implementation see my https://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift/24318861#24318861 – matt Nov 23 '20 at 16:13