[swift-evolution] ternary operator ?: suggestion

Craig Cruden ccruden at novafore.com
Thu Jan 7 04:55:25 CST 2016


It is partially contrived (hard coded, and simplified), but reality can get quite a bit more complex.  I tried to take a very simple understandable case and then reduce it to a very few parameters.

I still prefer the Scala syntax that uses “=>” “->" instead of “:”  or “!” between case and value - but Swift uses “:”.  At least an IDE / editor helps readability.  

I don’t like having to sprinkle “lets” all throughout the pattern matching.   The types of Int and Double were used because it is core, I would never use Double for anything financial - just a good “BigDecimal” equivalent.  I tried using implicit type conversion - but it playground did not like it so I just forced the issue :p



> On 2016-01-07, at 17:39:14, Charles Constant <charles at charlesism.com> wrote:
> 
> Craig, golly just looking at your example depresses me. I'm not saying it's contrived, it seems like real enough code. With the combination of our proposals, and the requirement to explicitly cast to Double... ugh, my eyes just glaze over.
> 
> Here's "where"...
> 
> let commission = trade ?
> 	case .Buy(let quantity, let price) where Double(quantity) * price > 10000:
>  		Double(quantity) * price * vipCommissionRate / 100
> 	case .Buy(let quantity, let price):
> 		Double(quantity) * price * commissionRate / 100
> 	case .Sell(let quantity, let price) where Double(quantity) * price > 10000:
> 		Double(quantity) * price * vipCommissionRate / 100
> 	case .Sell(let quantity, let price):
>     		Double(quantity) * price * commissionRate / 100
> 
> I also tried my favourite proposal:
> 
> let commission = trade ?
> 	.Buy(let quantity, let price) ! 
> 		Double(quantity) * price > 10000 ? 
> 			Double(quantity) * price * vipCommissionRate / 100 : 
> 			Double(quantity) * price * commissionRate / 100 : 
> 	.Sell(let quantity, let price) ! 
> 		Double(quantity) * price > 10000  ? 
> 			Double(quantity) * price * vipCommissionRate / 100 : 
> 			Double(quantity) * price * commissionRate / 100
> 
> Both of these are unreadable. I think my preferred example is slightly unreadable when it's indented the way I have here, but it would be a complete and total disaster as a single line... which people tend to do with ternary expressions :(  
> 
> 
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160107/41c64228/attachment.html>


More information about the swift-evolution mailing list