[swift-evolution] ternary operator ?: suggestion

Paul Ossenbruggen possen at gmail.com
Sun Dec 6 16:11:35 CST 2015


so the rule would have to be that the “switch" or “if" must return a value of compatible type. Not sure I love all the braces in the “if" case but it does follow the existing language rules with the exception that it must be have an else.

let thisColor = if condition { .Red }   // illegal for expressions but not statements

Can still do this for statements:
if condition {
	x = 40
}

likewise:
let thisColor = if condition { .Red } else { 21 } // illegal unless thisColor is Any 

unless: 
let thisColor : Any = if condition { .Red } else { 21 } // illegal unless thisColor is Any 

It would be nice to omit braces in this expression case but not for statements: 
let thisColor = if condition .Red else .Blue 

in statements braces would be required: 

if condition {
	x = 32
} else {
	y = 44
}

> >     }
> On Dec 6, 2015, at 1:52 PM, Alex Lew via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I agree that it's simplest to just reuse switch keyword, and keep braces. +1.  
> 
> Would you allow the same thing with if?
> 
> let thisColor = if condition { .Red } else { .Blue }
> 
> On Sun, Dec 6, 2015 at 4:44 PM, Rudolf Adamkovic <salutis at me.com <mailto:salutis at me.com>> wrote:
> > On 06 Dec 2015, at 22:35, thorsten--- via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
> 
> >
> > I would prefer the expression to match the statement. The only difference would be that all parts that were statements now have to be expressions.
> 
> +1
> 
> >
> > Therefore the switch-expression should simply look like follows:
> >
> > let thisColor = switch thatColor {
> >         case .Red: .Green // must be an expression
> >         default: .Yellow      // must be an expression
> >     }
> >
> > No returns needed in the case clauses.
> 
> This actually looks great. One simple rule and zero new keywords.
> 
> Readable and simple to learn.
> 
> Fantastic!
> 
> > Formatting this as a one-liner would just require adding semicolons (though I wouldn't recommend this).
> >
> > -Thorsten
> > _______________________________________________
> > swift-evolution mailing list
> > swift-evolution at swift.org <mailto:swift-evolution at swift.org>
> > https://lists.swift.org/mailman/listinfo/swift-evolution <https://lists.swift.org/mailman/listinfo/swift-evolution>
> 
>  _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-evolution <https://lists.swift.org/mailman/listinfo/swift-evolution>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151206/e03515fe/attachment.html>


More information about the swift-evolution mailing list