user2976267 user2976267 - 9 months ago 68
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

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