Hacker News new | ask | show | jobs
by zaksoup 2686 days ago
I'm not totally versed in Swift. In the example provided is it ambiguous because the closure captures `count` and count itself is being modified by the method calling the block?

I don't understand why this is an example of an unsafe operation. Wouldn't clearly defined behavior of closures clarify the "3 or 4" question?

1 comments

> I don't understand why this is an example of an unsafe operation. Wouldn't clearly defined behavior of closures clarify the "3 or 4" question?

I believe that it's possible to specify this, and that's basically the behavior we had before SE-0176 was implemented. The issue with this is that it was slower for a dubious benefit (the semantics are obscure and non-obvious), so it was decided that it's just better to disallow this and get the benefit of clear behavior and better optimization opportunities, at the cost of removing this somewhat uncommon and not-all-that-hard to-rewrite-for-clarity pattern.

> it was slower for a dubious benefit

Isn't this kind of arguable? The benefit is that it avoids the need to make unnecessary copies in some cases, as is basically acknowledged in the article:

> The exclusivity violation can be avoided by copying any values that need to be available within the closure

Right? And in addition to the local cost of the extra copy, there's also the more ubiquitous cost of these run-time checks. Yes, there's the potential benefit of better optimization due to the non-aliasing guarantee, but I think it's far from clear that it's an overall performance win.

While I think it's reasonable to adopt a universal "exclusivity of mutable references" policy in order to achieve memory safety and address a fear of a (vaguely-defined) notion of "mutable state and action at a distance" (referred to in the article), particularly for a language like Swift, I think it would be improper to dismiss the associated costs, or even to imply that the costs are well understood at this point. Or to imply that this policy is, at this point, known to be an optimal solution for achieving memory (or any other kind of code) safety.

I'm going to refer you to the proposal, which explains the rationale behind the change better than I possibly could: https://github.com/apple/swift-evolution/blob/master/proposa...