[swift-evolution] ternary operator ?: suggestion
Craig Cruden
ccruden at novafore.com
Thu Jan 7 23:11:43 CST 2016
I was thinking about this a bit, and was thinking that maybe we would not need a new keyword at all but just use `map` with pattern matching `case` clauses. It would mean adding `map` to individual values — or anything that we might want to use as input for matching.
Reference scala (section 8.5) pattern matching: http://www.scala-lang.org/docu/files/ScalaReference.pdf <http://www.scala-lang.org/docu/files/ScalaReference.pdf>
In scala inside `map` and `filter` (unfortunately not on things like `reduceLeft` or `foldLeft` you can specify pattern matching anonymous functions as such:
val num = List(1, 5, 7)
num.map {
case x if x < 5 => x + 1
case x => x - 1
}
output: List(2, 4, 6)
So if the pattern matching was added (I don’t believe Swift currently allows case classes in maps - but then I am rather junior in the language) Swift would not need a `match expression` it would simply be part of map and become something like:
let commission = trade.map {
case .Buy(let quantity, let price) where Double(quantity) * price > 10000 in
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
}
>
> But if we go with brackets then I would recommend something like this:
>
> let commission = match (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
> }
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160108/4a9bc320/attachment.html>
More information about the swift-evolution
mailing list