[swift-evolution] !? operator for ternary conditional unwrapping

Anton Zhilin antonyzhilin at gmail.com
Wed Feb 8 13:01:41 CST 2017


With Runes <https://github.com/thoughtbot/Runes>, this looks like:

(name1 <^> { "\"\($0)\"" }) ?? "null"

Runes defines <^> to have lower precedence than ??. Sadly, they all can’t
be in the same precedence group due to right associativity of ??.

2017-02-08 18:11 GMT+03:00 Tony Allevato via swift-evolution <
swift-evolution at swift.org>:

What you're asking for is already possible (avoiding the optional unwrap)
> by combining map() on Optional with ??:
>
> ```
> let name1: String? = "name"
> print(name1.map { "\"\($0)\"" } ?? "null")  // prints "\"name\""
>
> let name2: String? = nil
> print(name2.map { "\"\($0)\"" } ?? "null")  // prints "null"
> ```
>
> So I guess the question is, does simplifying that rise to the level of
> wanting a custom operator? I personally don't think it does, but I could
> see an argument being made that an operator with defined semantics might be
> a small amount clearer than map + ??. But I think the benefits would have
> to be very strong, though.
>
> And as other folks have mentioned, having "!" in the operator name is
> somewhat misleading, since when I see that I expect a trap to occur in nil
> cases.
>
​
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170208/03d2f7f1/attachment.html>


More information about the swift-evolution mailing list