I often like to have methods that take an optional closure as a callback if one is needed. So far, with Silver I am unable to do this. Here is a short Android example that does work, although a callback MUST be provided.
public class MainActivity: Activity {
public override func onCreate(savedInstanceState: Bundle!) {
super.onCreate(savedInstanceState)
ContentView = R.layout.main
doSomethingWithACallback() {
println("And I made it to the callback.")
}
}
private func doSomethingWithACallback( completion: () -> () ) {
println("I did something!")
completion()
}
}
LogCat: I/System.out( 2448): I did something!
LogCat: I/System.out( 2448): And I made it to the callback.
However, If I try to make the callback optional, a compiler complains “No Matching Overload”
public class MainActivity: Activity {
public override func onCreate(savedInstanceState: Bundle!) {
super.onCreate(savedInstanceState)
ContentView = R.layout.main
doSomethingWithAnOptionalCallback() { <------- No matching overload!
println("And I made it to the callback.")
}
}
private func doSomethingWithAnOptionalCallback( completion: ( () -> () )? ) {
println("I did something!")
if completion != nil {
completion!()
}
}
}
Instead of using an optional parameter to receive the closure, I tried setting it to an empty closure as a default if no callback was provided, but this yielded the compiler error, constant expected.
private func doSomethingWithACallback( completion: () -> () = { } ) { <- Constant expected
println("I did something!")
completion()
}
For now, my workaround is to always provide a callback and pass an empty closure when no callback is required.
public class MainActivity: Activity {
public override func onCreate(savedInstanceState: Bundle!) {
super.onCreate(savedInstanceState)
ContentView = R.layout.main
// I don't need a callback, but I have to pass it something!
doSomethingWithACallback() { }
}
private func doSomethingWithACallback( completion: () -> () ) {
println("I did something!")
completion()
}
}
LogCat: I/System.out( 2538): I did something!
Not a huge problem, but I’ve gotten so used to just omitting the closure when I don’t need a callback that I keep forgetting to add the { } after the function call. Plus, it’s not very pretty.
Am I missing something?