Ethan J. hopped into the swift-lang irc tonight asking why the following was possible and was there any difference between the two forms:
do { var x = try throwingFunction() try x = throwingFunction() } catch {}
The best I can come up with is that try
is applied to expressions not function calls, and the assignment expression is tried as a single unit.
You cannot, however, declare and try on the same side of the assignment
// let try x = throwingFunction() // nope // try let x = throwingFunction() // also nope
Got a better answer? Do let me know!
Update: Jon A asks: “But isn’t x = y a statement and not an expression?” As Mike Ash pointed out in our chat, assignments are still expressions. “It’s just that their type and value are not what you might expect” The following is legal Swift:
var a = 1 var b = 2 var c = a = b
And c
‘s type is ()
and its value is also ()
. Mike adds that this might be the only place in Swift where a type and a value of that type are written identically.
If you want to have more fun, you can put the try
just about anywhere in the following expression. Mike explains, “try
doesn’t actually do anything. It’s just that the compiler forces you to put it on any expression which can throw. [It acts] as a marker.”
And then there‘s:
Comments are closed.