That couldn't be the (hypothetical) syntax, since (unlike if let) it would have to shadow objectpermanently in the rest of the scope — wouldn't it? — a practice that Swift disallows elsewhere as confusing.
Also, by computing an optional result, you would then (presumably) carry the optional value forward into following statements. As I preached here, carrying optionals isn't a great idea in Swift.
If you had to do that, ugly or long-winded syntax would signal your intention more clearly, so it might be the better approach after all!
Edit:
To be clear, the "long-winded" version would have this shape:
let addedObject: Object?
if let object {
addedObject = add(object, for: key)
}
else {
addedObject = nil
}
I don' think that what OP meant, I think they meant these two fragments will be equivalent:
let x = let object ? add(object, for: key) : nil
let x = if let object { add(object, for: key) } else { nil }
and equally these two where the expression value is discarded:
let object ? add(object, for: key) : nil
if let object { add(object, for: key) } else { nil }
So the new object binding only exists within the ternary expression's first branch and not propagated outside – after all it would be a compilation error similar to let object = ... - object is already defined.
On the feature itself: it is a marginal improvement on one hand; on another hand the "ternary operation" probably isn't worth improving... "If we didn't have ternary operation itself by now would we introduce it now?" probably not.
I'm going to give this feature the benefit of the doubt, so +0.5.
+1, I’ve often wanted this. Regardless of how anyone feels about ternaries, the fact is they do exist and some people like them. Yes, you can do if or .map instead, and no they aren’t that bad, but this seems like an easy thing to add to ternaries for those who prefer them.
That said, it does raise the question of whether to add support for chaining conditions with commas as well. E.g. let result = let object, let key ? add(object, for: key) : nil
or let result = let object, isValid(object) ? add(object, for: key) : nil
Personally I don't think this is necessary or desirable. Ternaries should be concise and the commas here don't read as clearly as they do in an if statement.
[edit] Another possible consideration is whether only shorthand shadowing is allowed or if you can unwrap to a different name. let result = let unwrapped = object ? add(unwrapped, for: key) : nil
This looks very problematic so again I would think it best to avoid.