[swift-evolution] Code blocks and trailing closures

Slava Pestov spestov at apple.com
Mon Mar 20 18:30:40 CDT 2017


> On Mar 15, 2017, at 3:35 AM, Rien via swift-evolution <swift-evolution at swift.org> wrote:
> 
> What does the following code fragment do?
> 
> serverCert.write(to: certificateUrl) { showErrorInKeyWindow(message); return }
> 
> The only possible answer is: I don’t know.

No, that is incorrect.

The code block in question is either a training closure argument to serverCert.write(), or it is a syntax error.

We don’t allow ‘naked’ blocks in Swift. If you want to evaluate a closure and discard it, you have to use ‘_ =‘:

_ = { … }

If you want to just introduce a new lexical scope you have to use the ‘do’ keyword:

do {
  stuff
  return
}

> 
> The problem is finding out what the “return” statement will do.
> 
> Without knowing if the {...} is a code block or a trailing closure it is impossible to know what the return statement will do. It will either end the closure or it will end the function that contains this code block.
> 
> This could be disambiguated by using the same syntax as for lazy variables:

There’s no special syntax for lazy variables, this is just a trick for turning a statement into an expression. It works with non-lazy vars too:

var x = { some statement; return x }()

Slava

> 
> serverCert.write(to: serverCertificateUrl) { showErrorInKeyWindow(message: message); return }()
> 
> Now it is clear that the return statement will only terminate the (trailing) closure.
> 
> A question to the educators on the list: Is this a real problem?
> 
> Personally, I dislike this situation, but I am also ambivalent towards the solution I just described.
> 
> Regards,
> Rien
> 
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Balancingrock
> Project: http://swiftfire.nl
> 
> 
> 
> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list