[swift-evolution] Guaranteed closure execution
Gwendal Roué
gwendal.roue at gmail.com
Sun Apr 24 12:37:55 CDT 2016
> Le 23 avr. 2016 à 18:33, Timothy Wood <tjw at me.com> a écrit :
>
>
>
>> On Apr 23, 2016, at 5:56 AM, Gwendal Roué via swift-evolution <swift-evolution at swift.org>
> [...]
>>
>> Since @once actually implies @noescape (as described earlier in the thread), it can be shortened to:
> [...]
>
> I'm surprised that @once would imply @noescape.
I should try to rewrite my last answer, which did not explain why @once implies @noescape.
It is because @once is not a documenting token that is ignored by the compiler. Its goal is to be actually *used* by the compiler - and let the following snippet compile:
func f(closure: @noescape(once) () -> ()) { closure() }
let x: Int
f { x = 1 }
// use x without compiler complaining that x may be uninitialized.
For this pattern to work, the compiler needs to be able to prove that the closure has been called once at the end of the f function execution.
If the @once would only mean "will eventually be called once", the compiler would have the biggest difficulties proving it (one can not prove for example that NSOperation's completionBlock is called. It is a documentation given, not a provable fact), and the compiler would not accept the use of a variable initialized in a `once` closure, as in the above sample code.
That's why this proposal focuses on a `once` modifier that implies @noescape, AND allows the use of variables initialized in such a closure.
I said in an earlier post that this was a natural extension of SE-0061 "Add Generic Result and Error Handling to autoreleasepool() https://github.com/apple/swift-evolution/blob/master/proposals/0061-autoreleasepool-signature.md
Before SE-0061, we had to write:
var x: Int = 0
autoreleasepol {
x = 1
}
// use x
With SE-0061, we can write:
let x = autoreleasepol {
return 1
}
// use x
With this proposal, we can write:
let x: Int
let y: String
autoreleasepol {
x = 1
y = "foo"
}
// use x and y
Gwendal Roué
More information about the swift-evolution
mailing list