4 ms·
I will say that I've always been uncomfortable with binding new values inside an if-statement's test. As far as syntax goes, it's a good thing that it's possib
by bunderbunder 12y ago
I will say that I've always been uncomfortable with binding new values inside an if-statement's test.
As far as syntax goes, it's a good thing that it's possible: I'm assuming here that in Swift every statement is an expression, which is a good thing, and such a feature naturally means that doing this sort of thing should be possible. But stylistically it just feels ugly to me. I don't know if Swift has an equivalent to either of the following, but I'd prefer either of them as a cleaner idiom:
Null-coalescing a la C#:
self.imageUrl = json["imageUrl"].string
?? "http://example.com/empty-avatar.png";
Pattern matching a la F#:
self.imageUrl <-
match json["imageUrl"].string with
| Some(value) -> value
| None -> "http://example.com/empty-avatar.png"
- mikeash 12y agoBoth of those work in Swift too. The ?? operator exists verbatim, and the matching can be done using a switch/case statement. Unfortunately, it is not true that every Swift statement is an expression. The if/let construct is actually a special case. That means that you can't do something like: if (let x = foo) && (let y = bar) { ... Which is too bad.
- drivingmenuts 12y agoI get the binding a value inside an if statement. if (i=3*someFunctionResult()) { ... blah using i ... } makes perfect sense to me. The "let" seems unnecessary and, for lack of a better term, unpoetic. Aside from which, the use of let to define a constant in the middle of an if statement is about as wrong as you can get, in my opinion. Define your constants at the top or in another file, FFs.
- bunderbunder 12y ago'let' doesn't define a constant, it binds an immutable value. The semantic difference is enormous. A constant has infinite lifetime and must be known at compile time. A let-binding has limited scope and can be bound a run-time. In a language like Swift that distinguishes between mutable and immutable variables, a 'let' or 'var' is needed to indicate to the compiler what kind of of variable you're trying to create. Beyond that, it also makes for a cleaner language. Creating a special syntax for let statements that only applies inside the condition for an if-statement (and presumably also loops) just so you can avoid typing a few letters approaches PHP levels of unholy grammar pollution.