OdNairy
(Roman Gardukevich)
1
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?
nuclearace
(Erik Little)
2
Could you do something like
func t(_ b: @autoclosure () -> String?) -> String {
return b() ?? "hello"
}
print(t(nil))
OdNairy
(Roman Gardukevich)
3
Unfortunately, not. I need this optional to make the rest system work as expected.
nuclearace
(Erik Little)
4
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.
griotspeak
(TJ Usiyan)
5
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
OdNairy
(Roman Gardukevich)
8
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
6 Likes
I came into a situation today where I would have liked to have this.
2 Likes
clayellis
(Clay Ellis)
11
This construction seems to work:
func foo(value: @autoclosure () -> Int? = { nil }()) {
//...
}
2 Likes