[swift-dev] Reason for call only non-escaping parameter
Dimitri Racordon
Dimitri.Racordon at unige.ch
Wed May 31 15:17:42 CDT 2017
Thanks for your answer.
I agree that it may not be the most useful feature (although I’m sure we could find not-so-contrived yet useful use-cases). Anyway, I guess that discussion would rather belong to the evolution list :)
I was more wondering if there were situations where such local assignments would have to be disallowed.
Best,
Dimitri
On 31 May 2017, at 22:10, John McCall <rjmccall at apple.com<mailto:rjmccall at apple.com>> wrote:
On May 31, 2017, at 12:21 PM, Dimitri Racordon via swift-dev <swift-dev at swift.org<mailto:swift-dev at swift.org>> wrote:
Hi everyone,
I failed to find the reason why Swift does not allows a non-escaping parameter to be assigned to a local variable. Here is a minimal example:
func f(_ closure: () -> Int) {
let a = closure
}
I do understand that assigning a non-escaping closure to a variable whose lifetime exceeds that of the function would (by definition) violate the non-escaping property. For instance, doing that is understandably illegal:
var global = { 0 }
func f(_ closure: () -> Int) {
global = closure
}
But in my first example, since `a` is stack allocated, there’s no risk that `closure` escapes the scope of `f`.
Is there some use case I’m missing, where such assignment could be problematic?
Or is this a limitation of the compiler, which wouldn't go all the way to check whether the lifetime of the assignee is compatible with that of the non-escaping parameter may exceed that of the variable it is assigned to?
Thank you very much for your time and your answer.
Examples like yours, where a non-escaping closure parameter has a new constant name bound to it, are supportable but rather pointless — as a programmer, why have two names for the same value? Examples that would be more useful, like assigning the closure into a local variable or allowing it to be used in a more complex expression (like ? :), complicate the analysis for non-escaping closures in a way that would significantly subvert their purpose.
John.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20170531/e60ac512/attachment.html>
More information about the swift-dev
mailing list