简体   繁体   中英

Swift 5 : How do you pass a function to run inside a function () Noobie in swift

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? 
 

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") }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM