Optional closure with @autoclosure

Hi all
I’ve tried to make a function with @autoclosure for optional closure like func foo(myArg: @autoclosure (() -> String)? = nil) but got an error @autoclosure attribute only applies to function types.
Is there any way to do it or I do it in a wrong way?

Could you do something like

func t(_ b: @autoclosure () -> String?) -> String {
  return b() ?? "hello"
}

print(t(nil))

Unfortunately, not. I need this optional to make the rest system work as expected.

Then no, you can’t currently use @autoclosure like this, so you’ll have to manually create the closures. Which is the same effect, but without the nice syntactic sugar.

Is it an acceptable solution to make two separate methods where one calls the other with nil?

foo() {
foo(myArg: nil)
}
foo(myArg: @autoclosure () -> String) = nil)

I’m not aware of a way to do this, but extending swift to support this would be reasonable and inline with how @escaping works.

-Chris

7 Likes

Wouldn’t it make ambiguous constructs ?

func foo(args: @autoclosure (() -> String?)?) {}

foo(args: nil)

Should it call foo with args = nil or should it call it with arg = { return nil } ?

4 Likes

Very good question.

May be it makes sense to use nil as args = nil? What is the process to discuss this with community?

We should just allow this instead of come up with new hacks:

func foo(bar: (@autoclosure () -> String)? = nil) { ... }

var something: @autoclosure () -> String
5 Likes

I came into a situation today where I would have liked to have this.