I have been wondering about the same thing @michelf just proposed. Swift already has idiomatic ways to talk about things that are "optional"; what if we use that same idiom? What if we use ? and ! to mark the required-ness or non-required-ness of trailing closures?
// Label 'handler' is marked optional using '?'. The label
// may be present in a trailing closure, or it may be
// elided.
func requestAccess(to resource: String, handler?: ()->Void)
// These are both okay, because the label is optional
requestAccess(to: "camera") { /* do stuff */ }
requestAccess(to: "camera")
handler: { /* do stuff */ }
// Label 'handler' is marked *required* using '!'. The label
// *must* be present when called with a trailing closure
func requestAccess(to resource: String, handler!: ()->Void)
// Trailing closure label is *required*
requestAccess(to: "camera")
handler: { /* do stuff */}
Labels without ? or ! would continue to work as they currently do
// Existing behavior unchanged; trailing closure label elided.
func requestAccess(to resource: String, handler: ()->Void)
// Usage remains unchanged
requestAccess(to: "camera") { /* do stuff */ }
// Explicitly requesting no trailing closure. (This already
// works, but gains new significance with the possibility
// of single-trailing-closure labels.)
func requestAccess(to resource: String, _ handler: ()->Void)
// Usage remains unchanged
requestAccess(to: "camera") { /* do stuff */ }
Of course, if a parameter label is marked as optional, then it seems like it should be optional in the non-trailing syntax as well?
func requestAccess(to resource: String, handler?: ()->Void)
// These are both okay too, I guess?
requestAccess(to: "camera", handler: { /* do stuff */ })
requestAccess(to: "camera", { /* do stuff */ })
We don't currently have a way to force a parameter to be called with a trailing closure, so any decorator that affects the label in trailing-closure syntax is necessarily conflated with the non-trailing syntax, but maybe that's okay?
What do you think?