user2976267 user2976267 - 3 months ago 14
Swift Question

Swift's analog for Java's Runnable

Surprisingly, Google search returned me nothing about that.
What I do on Android :

void doSomethng(Runnable r){
r.run();
}


Which is simply passing some block of code in a context of a sending class and then execute this block by demand.
How can I do the same with Swift for iOS?

Avt Avt
Answer

Syntax for function that gets a block without parameters and does not have a return value is following:

func doSomethng(runnable: () -> ()){
   runnable()
}

If you are going to use such blocks widely you could define a special type for it:

typealias Runnable = () -> ()

func doSomethng2(runnable: Runnable){
    runnable()
}

I also suggest you to check this site fuckingclosuresyntax.com to quickly get the idea of block/closure's syntax in Swift.

If you need to run blocks in a separate thread check GCD

Comments