user2976267 user2976267 - 1 year ago 108
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){;

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 Source

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

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

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

typealias Runnable = () -> ()

func doSomethng2(runnable: Runnable){

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download