Search code examples
swiftsyntaxclosures

How to create empty closure properly?


I have a class with a closure as a property:

class MyClass{
     var onChange = {}

     func foo(){
         onChange()
     }
}

A behaviour implemented in closure is used in method foo:

var c = MyClass()
c.onChange = {
    println("something is changed");
}
c.foo()  // prints 'something is changed'

It's easy to make closures with an argument like {(n: Int) -> Void in println(n); } but how to create a closure without input arguments?

I tried to use {}, {in}, etc., but it gave a compilation error.

How to create empty closure properly?


Solution

  • If I understood your question correctly, you could use:

    var closure = {() -> () in
        return
    }